{

Dart| Flutter How to: String replace method


How to String replace method Dart and Flutter

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

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart