Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace Strings in Dart

Tags:

find

replace

dart

I'm using flutter for this app and I'm having trouble with the app's logic. Any help is much appreciated.

App goal: Decode(replace) all input abbreviation to words by: -User inputs text via text box -App looks for any abbreviations(several) and replaces the abbreviation only with text.

I was able to do it will a few abbreviation but with my case all abbreviation should be in the input text or it wouldn't work or the second index wont work. I tried several ways which didn't work, I'm using 2 list for the abv and corresponding text.

Here is the code.

List<String> coded = ["GM", "HOT", "YAH"]; //ABV list
List<String> decoded = ["Gmail", "Hotmail", "Yahoo"]; //corresponding list 
Map<String, String> map = new Map.fromIterables(coded, decoded);

String txt = "HOT was the best until GM took over"; //input text

void main() {
  if ((txt.contains(coded[0]))) { //GM
    String result = txt.replaceAll(coded[0], decoded[0]); //Replace with Gmail

    print(result);
  }
  else if ((txt.contains(coded[0])) && (txt.contains(coded[1]))) {
    String result = (txt.replaceAll(coded[0], decoded[0]));
    (txt.replaceAll(coded[1], decoded[1]));

    print(result);
  }
  else if ((txt.contains(coded[0])) && (txt.contains(coded[1])) && (txt.contains(coded[2]))) {
    String result = txt.replaceAll(coded[0], decoded[0]);
    txt.replaceAll(coded[1], decoded[1]);
    txt.replaceAll(coded[2], decoded[2]);

    print(result);
  }
  else {
    print(txt);
  }
} 
like image 629
M. Romaithi Avatar asked Oct 02 '18 19:10

M. Romaithi


People also ask

How do you replace multiple characters in a string in flutter?

You can use a RegExp to match the characters you need to replace, and then use `String. replaceAllMapped` to find those characters in a string and replace them with something else.


2 Answers

For others coming here based on the question title, use replaceAll:

final original = 'Hello World';
final find = 'World';
final replaceWith = 'Home';
final newString = original.replaceAll(find, replaceWith);
// Hello Home
like image 104
Suragch Avatar answered Oct 29 '22 16:10

Suragch


What you want can be done quite easily with fold:

List<String> coded = ["GM", "HOT", "YAH"]; //ABV list
List<String> decoded = ["Gmail", "Hotmail", "Yahoo"]; //corresponding list 
Map<String, String> map = new Map.fromIterables(coded, decoded);

String txt = "HOT was the best until GM took over"; //input text

void main() {
  final result = map.entries
    .fold(txt, (prev, e) => prev.replaceAll(e.key, e.value));
  print(result);
}

Basically you will iterate on map entries (pairs of key/value). fold takes an initial value (txt in your case) and a function to update the previous value with the current element that is iterated. After each iteration the result has replaced all ABV.

like image 22
Alexandre Ardhuin Avatar answered Oct 29 '22 15:10

Alexandre Ardhuin