{

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 substring

String replaceAll(Pattern from, String replace)

from string is a pattern that replaces 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 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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example