Dart – How to split a String

Like other languages, Dart provides .split(pattern) method to split a string into a list of sub-strings.

Let’s look at below example, it splits a string by spaces:

void main() {
  String str = 'This is a test String.';
  var strList = str.split(' ');
  print(strList);
}


Output

[This, is, a, test, String.]


If the provided pattern/regex is an empty string, it will split your string into single characters:

void main() {
  String str = 'This is a test String.';
  var strList = str.split('');
  print(strList);
}


Output

[T, h, i, s,  , i, s,  , a,  , t, e, s, t,  , S, t, r, i, n, g, .]


If you are good at Regular Expression (RegExp), you can split the string using complicated patterns. In below example, we split string by any number:

void main() {
  const String str = 'This1is2a3test4String.';
  final strList = str.split(RegExp('[0-9]'));
  print(strList);
}


Output

[This, is, a, test, String.]

Tagged : / / /
Subscribe
Notify of
guest

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Bill
Bill
9 months ago

This example does not work:

void main() {
  String str = 'This1is2a3test4String.';
  var strList = str.split(r'[0-9]');
  print(strList);
}
2
0
Would love your thoughts, please comment.x
()
x