OneBite.Dev - Coding blog in a bite size

Split A String By Empty Space In Dart

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

In the world of programming, the task of splitting a string by empty space is a common one. This activity is essential in preprocessing text-based data; it allows for the separation of single words or phrases from a larger block of text. The Dart programming language, commonly used in Google’s Flutter, also provides a straightforward approach to achieve this task.

Code snippet: Splitting a String by Empty Space in Dart

Here is a simple Dart code snippet that demonstrates the task:

void main() {
  String str = "Hello World! How are you?";
  var list = str.split(' ');
  print(list);
}

In the given code, the string “Hello World! How are you?” is split by empty spaces to separate each word into an independent entity, then these words are printed out as elements of a list.

Code Explanation for Splitting a String by Empty Space in Dart

Going through the code step by step:

  1. String str = "Hello World! How are you?"; 

    Here, a String str is created, holding “Hello World! How are you?” as its value.

  2. var list = str.split(' ');

    In the next line, the string’s split() function is called with an empty space ’ ’ as the delimiter. The split() function is a built-in Dart method that splits a string around matches of the given delimiter and returns a list of substrings. Since we provided an empty space as the delimiter, this function will separate str into substrings each time it encounters a space.

  3. print(list);

    Finally, the print statement prints out the list that was returned from the previous operation. The output will be: [Hello, World!, How, are, you?]

To sum it up, the above Dart code snippet helps in splitting the string “Hello World! How are you?” by empty spaces and storing these independent substrings into a list. This operation is common in many programming applications, including text data analysis and natural language processing.

dart