OneBite.Dev - Coding blog in a bite size

Replace A Substring Within A String In Dart

Code snippet for how to Replace A Substring Within A String In Dart with sample and detail explanation

Dart is an efficient and intuitive programming language used widely for mobile, web, and desktop apps. Sometimes you may need to replace a substring within a string, so let’s explore how to do this in Dart.

Code Snippet: Replace a Substring within a String in Dart

Here’s a simple code snippet that demonstrates how to replace a substring within a string in Dart.

void main() {
  String str = "Hello, world!";
  String newStr = str.replaceAll("world", "Dart");
  print(newStr);
}

In this program, “world” is the substring we’re looking to replace with “Dart” in our input string.

Code Explanation: Replace a Substring within a String in Dart

Now, let’s break down the code step by step.

  1. Initialize a new Dart application with the void main() function. This is the entry point of a Dart program.

  2. Declare a new string str with the value “Hello, world!“. This line of code is creating a new string variable named str and assigns “Hello, world!” as its initial value.

  3. In the next line, we create a new string newStr. We apply the replaceAll() function on str by writing str.replaceAll("world", "Dart"). The replaceAll() method is a string method in Dart which replaces all instances of a substring from the current string with a new provided string.

  4. The replaceAll() function takes two arguments. The first one is the substring you wish to replace, and the second one is the string to replace it with. In this case, we’re looking for “world” and we want to replace it with “Dart”.

  5. Finally, the new string, “Hello, Dart!” is printed to the console with the print(newStr) function.

This simple program perfectly demonstrates how to replace a substring within a string in Dart. Learning to manipulate strings is integral to most programming tasks, and Dart makes the process straightforward and easy.

dart