Dart String split()
Syntax & Examples

Syntax of String.split()

The syntax of String.split() method is:

 List<String> split(Pattern pattern) 

This split() method of String splits the string at matches of pattern and returns a list of substrings.

Parameters

ParameterOptional/RequiredDescription
patternrequiredthe pattern to split the string at matches

Return Type

String.split() returns value of type List<String>.



✐ Examples

1 Split String by Dash

In this example,

  1. We have a string str containing '1-2-3-4-5'.
  2. We use the split() method to split the string at each occurrence of '-'.
  3. The resulting substrings are stored in a list named parts.
  4. We print the parts to standard output.

Dart Program

void main() {
  String str = '1-2-3-4-5';
  List<String> parts = str.split('-');
  print('Parts: $parts');
}

Output

Parts: [1, 2, 3, 4, 5]

2 Split String by Comma

In this example,

  1. We have a string str containing 'A,B,C,D,E'.
  2. We use the split() method to split the string at each occurrence of ','.
  3. The resulting substrings are stored in a list named parts.
  4. We print the parts to standard output.

Dart Program

void main() {
  String str = 'A,B,C,D,E';
  List<String> parts = str.split(',');
  print('Parts: $parts');
}

Output

Parts: [A, B, C, D, E]

3 Split String by Comma

In this example,

  1. We have a string str containing 'apple,banana,grape'.
  2. We use the split() method to split the string at each occurrence of ','.
  3. The resulting substrings are stored in a list named parts.
  4. We print the parts to standard output.

Dart Program

void main() {
  String str = 'apple,banana,grape';
  List<String> parts = str.split(',');
  print('Parts: $parts');
}

Output

Parts: [apple, banana, grape]

Summary

In this Dart tutorial, we learned about split() method of String: the syntax and few working examples with output and detailed explanation for each example.