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.]
This example does not work: