Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace only one character in a string in Dart?

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.

like image 368
Anuran Barman Avatar asked Aug 29 '18 18:08

Anuran Barman


People also ask

How do you replace a character in a string in darts?

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 .

How do you remove part of a string in darts?

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.

How do you remove part of a string in flutter?

String s = "one. two"; //Removes everything after first '. ' String result = s. substring(0, s.


3 Answers

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.

like image 179
Dinesh Balasubramanian Avatar answered Oct 10 '22 03:10

Dinesh Balasubramanian


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
like image 27
Suragch Avatar answered Oct 10 '22 03:10

Suragch


You can use replaceAll().

String string = 'string';
final letter='i';
final newLetter='a';
string = string.replaceAll(letter, newLetter);  // strang
like image 13
Youssef Elmoumen Avatar answered Oct 10 '22 05:10

Youssef Elmoumen