Skip to content

Instantly share code, notes, and snippets.

@jossef
Last active May 23, 2020 11:20
Show Gist options
  • Select an option

  • Save jossef/e9a5a8a5ff803092c76a26d6721bfaf4 to your computer and use it in GitHub Desktop.

Select an option

Save jossef/e9a5a8a5ff803092c76a26d6721bfaf4 to your computer and use it in GitHub Desktop.
dart string split with maximum
import 'dart:convert';
List<String> split(String string, String separator, {int max = 0}) {
var result = List<String>();
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
string = string.substring(index + separator.length);
}
return result;
}
void main() {
print(json.encode(split("a=b=c", "="))); // ["a","b","c"]
print(json.encode(split("a=b=c", "=", max: 1))); // ["a","b=c"]
print(json.encode(split("", ""))); // [""]
print(json.encode(split("foo", ""))); // ["foo"]
print(json.encode(split("foo", "foo"))); // ["",""]
print(json.encode(split("a=", "="))); // ["a",""]
}
@jossef
Copy link
Author

jossef commented May 23, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment