Last active
May 23, 2020 11:20
-
-
Save jossef/e9a5a8a5ff803092c76a26d6721bfaf4 to your computer and use it in GitHub Desktop.
dart string split with maximum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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",""] | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
link to dartpad.dev -> https://dartpad.dev/e9a5a8a5ff803092c76a26d6721bfaf4
stackoverflow answer -> Flutter/Dart: Split string by first occurrence