OneBite.Dev - Coding blog in a bite size

Split A String By Comma Sign In Dart

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

Dart, a general-purpose programming language, is an easy-to-use, efficient tool for coding. In this brief article, we’ll take a look at how to split a string by a comma in Dart.

Code Snippet: Splitting a String by Comma

Below is a concise code snippet illustrating how to divide a string by a comma.

void main() {
  String str = 'The, quick, brown, fox, jumps';
  List<String> strList = str.split(', ');
  
  print(strList);
}

When you run this code, the output will display 'The', 'quick', 'brown', 'fox', 'jumps'.

Code Explanation: Splitting a String by Comma

In the code snippet, we first define the main() function which is the starting point of a Dart program.

Inside the main() function, we declare a string ‘str’ that contains a simple sentence with words separated by commas.

String str = 'The, quick, brown, fox, jumps';

Next, we use the split() method to divide the string into a list of substrings. This method splits the string every time it encounters the specified delimiter - in our case, a comma followed by a space ', '.

List<String> strList = str.split(', ');

The split() function returns a new list of strings. Here, strList becomes a list of strings with each word of the sentence as an individual element.

Finally, we use the print() function to output the strList to the console.

print(strList);

In conclusion, splitting a string by a comma in Dart can be performed easily by utilizing the split() function.

dart