在Dart中查找和替换字符串 [英] Find and Replace Strings in Dart

查看:2585
本文介绍了在Dart中查找和替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为该应用程序使用Flutter,但在应用程序逻辑方面遇到了麻烦。

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

应用目标:
-用户通过文本框
输入文本来解码(替换)单词的缩写-App查找任何缩写(几个),并且仅用文本替换该缩写。

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.

我能够做到这一点,但我的情况下所有缩写均应为在输入文本中将不起作用,或者第二个索引将不起作用。
我尝试了几种无效的方法,我在abv和相应的文本中使用了2个列表。

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.

下面是代码。

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


推荐答案

其他根据问题标题来到这里的用户,请使用 replaceAll

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

这篇关于在Dart中查找和替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆