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

Viewed 33225

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.

6 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.

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

with this line you can replace the $ symbol with a blank space ''

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

You can use this function, just modified Dinesh's answer

      String _replaceCharAt(
          {required String character,
          required int index,
          required String oldString}) {
        if (oldString.isEmpty) {
          return character;
        } else if (index == oldString.length) {
          return oldString.substring(0, index) + character;
        } else if (index > oldString.length) {
          throw RangeError('index value is out of range');
        }
    
        return oldString.substring(0, index) +
            character +
            oldString.substring(index + 1);
      }

You can just use this in build function to do it.

s.replaceRange(start, end, newString)
Related