splitSpaceDelimitedString function
Returns a List of space-delimited tokens efficiently split from the specified string
.
Useful for splitting CSS className strings into class tokens, or data-test-id
values into individual test IDs.
Handles leading and trailing spaces, as well as token separated by multiple spaces.
Example:
splitSpaceDelimitedString(' foo bar baz') // ['foo', 'bar', 'baz']
Implementation
List<String> splitSpaceDelimitedString(String string) {
const int SPACE = 32; // ' '.codeUnits.first;
List<String> strings = [];
int start = 0;
while (start != string.length) {
while (string.codeUnitAt(start) == SPACE) {
start++;
if (start == string.length) {
return strings;
}
}
int end = start;
while (string.codeUnitAt(end) != SPACE) {
end++;
if (end == string.length) {
strings.add(string.substring(start, end));
return strings;
}
}
strings.add(string.substring(start, end));
start = end;
}
return strings;
}