简体   繁体   English

在 Dart 中查找和替换字符串

[英]Find and Replace Strings in 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.我尝试了几种不起作用的方法,我使用 2 个列表作为 abv 和相应的文本。

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);
  }
} 

For others coming here based on the question title, use replaceAll :对于根据问题标题来到这里的其他人,请使用replaceAll

final original = 'Hello World';
final find = 'World';
final replaceWith = 'Home';
final newString = original.replaceAll(find, replaceWith);
// Hello Home

What you want can be done quite easily with fold :使用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. fold采用一个初始值(在您的情况下为txt )和一个函数,用于使用迭代的当前元素更新前一个值。 After each iteration the result has replaced all ABV.每次迭代后,结果都替换了所有 ABV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM