OneBite.Dev - Coding blog in a bite size

Split A String In Dart

Code snippet for how to Split A String In Dart with sample and detail explanation

In programming, string manipulation is a common task and the need to split a string can often arise. This article will provide a simple tutorial on how to split a string in Dart programming language.

Code snippet for Splitting a String in Dart

Below is a simple Dart code snippet that demonstrates how to split a string.

void main() {
  String str = "Hello World!";
  var strArray = str.split(" ");
  
  print(strArray);
}

In this code, we are splitting the string ‘Hello World!’ wherever a space character ’ ’ is found.

Code Explanation for Splitting a String in Dart

Let’s break down the above code snippet and explain it step by step.

  1. void main() {} - This is the main method, which marks the entry point of our Dart program.

  2. String str = "Hello World!"; - Here, we declare a string named str and initialize it with the value "Hello World!".

  3. var strArray = str.split(" "); - This is where the string splitting happens. The split() method is a built-in method in Dart that splits a string around matches of the given delimiter. In this case, it splits the string every time it encounters a space character ’ ‘. The result is a list of substrings.

  4. print(strArray); - This line prints the resulting list to the console.

When you run this code, it will print: [Hello, World!]. This means the string has been successfully split into two separate strings - "Hello" and "World!", based on the space delimiter.

That’s it! That’s how you can effortlessly split a string into a list of substrings in Dart. You can replace the space character with whatever character you wish to split the string on. Try to experiment with different characters and multiple words.

dart