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() {
  String str = 'This1is2a3test4String.';
  var strList = str.split(r'[0-9]');
  print(strList);
}

Output:

[This, is, a, test, String.]
Spread the love
Tagged : / / /

Leave a Reply

Your email address will not be published. Required fields are marked *