如何在 Dart 中只替换字符串中的一个字符?

Anu*_*man 17 string dart flutter

我试图只替换字符串飞镖中的一个字符,但找不到任何有效的方法。由于字符串不是 Dart 中的数组,我无法通过索引直接访问字符,并且没有内置函数可以做到这一点。这样做的有效方法是什么?

目前我正在这样做:

List<String> bedStatus = currentBedStatus.split("");
   bedStatus[index]='1';
   String bedStatusFinal="";
   for(int i=0;i<bedStatus.length;i++){
      bedStatusFinal+=bedStatus[i];
   }
}
Run Code Online (Sandbox Code Playgroud)

index 是一个intcurrentBedStatus是我试图操作的字符串

Din*_*ian 15

在特定索引处替换:

由于String在DART不变的 参考,我们不能编辑像

stringInstance.setCharAt(index, newChar)
Run Code Online (Sandbox Code Playgroud)

满足要求的有效方法是:

String hello = "hello";
String hEllo = hello.substring(0, 1) + "E" + hello.substring(2);
print(hEllo); // prints hEllo
Run Code Online (Sandbox Code Playgroud)

进入一个函数

String replaceCharAt(String oldString, int index, String newChar) {
  return oldString.substring(0, index) + newChar + oldString.substring(index + 1);
}
replaceCharAt("hello", 1, "E") //usage
Run Code Online (Sandbox Code Playgroud)

注意: index在上面的函数中是基于零的


Sur*_*gch 11

您可以使用replaceFirst().

final myString = 'hello hello';
final replaced = myString.replaceFirst(RegExp('e'), '*');  // h*llo hello
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想替换第一个,您可以使用开始索引:

final myString = 'hello hello';
final startIndex = 2;
final replaced = myString.replaceFirst(RegExp('e'), '*', startIndex);  // hello h*llo
Run Code Online (Sandbox Code Playgroud)


You*_*men 5

您可以使用replaceAll()。

String string = 'string';
final letter='i';
final newLetter='a';
string = string.replaceAll(letter, newLetter);  // strang
Run Code Online (Sandbox Code Playgroud)


小智 5

通过这一行,您可以$用空格 '' 替换该符号

'${double.parse (_priced.toString (). replaceAll (' \ $ ',' ')) ?? '\ $ 0.00'}' 
Run Code Online (Sandbox Code Playgroud)
String x = _with.price.toString (). ReplaceAll ('\ $', '')) ?? '\ $ 0.00',
Run Code Online (Sandbox Code Playgroud)