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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)