In Dart splitting of a string can be done with the help split string function in the dart. It is a built-in function use to split the string into substring across a common character.
Syntax:
string_name.split(pattern)
This function splits the string into substring across the given pattern and then store them to a list.
Example1:
Splitting a string across space.
// Main function
void main() {
// Creating a string
String g = "Welcome to J&J !!";
// Splitting the string
// across spaces
print(g.split(" "));
}
Output:
[Welcome, to, J&J, !!]
Example2:
Splitting each character of the string.
// Main function
void main() {
// Creating a string
String g = "WelcometoJ&J";
// Splitting each
// character of the string
print(g.split(""));
}
Output:
[W, e, l, c, o, m, e, t, o, J, &, J]
Apart from the above pattern, the pattern can also be a regex. It is useful when we have to split across a group of characters like numbers, special characters, etc.
Example 3:
Splitting a string across any number present in it. (Using regex)
// Main function
void main() {
// Creating a string
String g = "Splitting1a2string3across4any5number6present7in8it.";
// Splitting each character
// of the string
print(g.split(new RegExp(r"[0-9]")));
}
Output:
[Splitting, a, string, across, any, number, present, in, it.]