Dart| Flutter How to: String replace method
The string is an immutable class. There is no method such as setCharAt() with an index like in java.
We can do multiple ways to replace a character or substring in a String
String replace a letter using substring in dart example
This example, Replaces the one the character with a new character in a given string.
str.substring(0, 2) returns the substring with the start and end index. str.substring(3): returns the substring start index to the remaining string
Here is an example to replace a letter from a string of characters
void main() {
var str = "welcome john";
print(str); //welcome john
str = str.substring(0, 2) + "L" + str.substring(3);
print(str);//weLcome john
}
Output:
welcome john
weLcome john
String replace a letter using replaceAll in dart example
This example uses the String replaceAll method replaces the substring
String replaceAll(Pattern from, String replace)
from
string is a pattern that replaces the replace
string.
It returns the new string
Here is an example
void main() {
var str = "welcome john";
print(str); //welcome john
str = str.replaceAll("j", "k");
print(str); //welcome kohn
}
Output:
welcome john
welcome kohn
String replaces a substring with replaceFirst
It is using replaceFirst
with a regular expression
void main() {
var str = "welcome john";
print(str); //welcome john
str = str.replaceFirst(RegExp('h'), "n");
print(str); //welcome jonn
}
Output:
welcome john
welcome jonn
Conclusion
Learn multiple ways to replace a letter or character or substring in a string