partialSplit method

List<String> partialSplit(
  1. Pattern separatorPattern,
  2. int count
)

A version of String.split that limits splitting to return a List of at most count items.

count must be non-negative. If count is 0, returns an empty List.

If splitting this String would result in more than count items, the final element will contain the unsplit remainder of this String.

If splitting this String would result in fewer than count items, returns a List with only the split substrings.

Implementation

// Based on <https://stackoverflow.com/a/76039017/>.
List<String> partialSplit(Pattern separatorPattern, int count) {
  assert(count >= 0);

  var tokens = <String>[];

  if (count == 0) {
    return tokens;
  }

  for (var tokenInterval in _lazySplit(separatorPattern)) {
    if (tokens.length + 1 == count) {
      tokens.add(substring(tokenInterval.start));
      break;
    }

    tokens.add(substring(tokenInterval.start, tokenInterval.end));
  }

  return tokens;
}