I am trying to replace only one character in a string dart but can not find any efficient way of doing that. As string is not array in Dart I can't access the character directly by index and there is no function coming in-built which can do that. What is the efficient way of doing that?
Currently I am doing that like below:
List<String> bedStatus = currentBedStatus.split("");
bedStatus[index]='1';
String bedStatusFinal="";
for(int i=0;i<bedStatus.length;i++){
bedStatusFinal+=bedStatus[i];
}
}
index is an int and currentBedStatus is the string I am trying to manipulate.
To replace all occurrences of a substring in a string with new substring, use String. replaceAll() method. The method returns a new string with all string matchings of given pattern replaced with newSubString . You can give a string for pattern .
To replace all the substring of a string we make use of replaceAll method in Dart. This method replaces all the substring in the given string to the desired substring.
String s = "one. two"; //Removes everything after first '. ' String result = s. substring(0, s.
Replace at particular index:
As String
in dart is immutable refer, we cannot edit something like
stringInstance.setCharAt(index, newChar)
Efficient way to meet the requirement would be:
String hello = "hello";
String hEllo = hello.substring(0, 1) + "E" + hello.substring(2);
print(hEllo); // prints hEllo
Moving into a function:
String replaceCharAt(String oldString, int index, String newChar) {
return oldString.substring(0, index) + newChar + oldString.substring(index + 1);
}
replaceCharAt("hello", 1, "E") //usage
Note: index
in the above function is zero based.
You can use replaceFirst()
.
final myString = 'hello hello';
final replaced = myString.replaceFirst(RegExp('e'), '*'); // h*llo hello
Or if you don't want to replace the first one you can use a start index:
final myString = 'hello hello';
final startIndex = 2;
final replaced = myString.replaceFirst(RegExp('e'), '*', startIndex); // hello h*llo
You can use replaceAll().
String string = 'string';
final letter='i';
final newLetter='a';
string = string.replaceAll(letter, newLetter); // strang
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With