strtok method

String? strtok(
  1. String? str,
  2. String delim
)

Tokenizes a string.

In C, the first call takes the string, and subsequent calls take null. We simulate this by accepting a nullable string. If str is provided, tokenization starts fresh. If str is null, tokenization continues from the last saved state.

Implementation

String? strtok(String? str, String delim) {
  if (str != null) {
    _strtokState = str;
  }

  if (_strtokState == null || _strtokState!.isEmpty) {
    return null;
  }

  // Skip leading delimiters
  int start = 0;
  while (start < _strtokState!.length && delim.contains(_strtokState![start])) {
    start++;
  }

  if (start >= _strtokState!.length) {
    _strtokState = null;
    return null;
  }

  // Find end of token
  int end = start;
  while (end < _strtokState!.length && !delim.contains(_strtokState![end])) {
    end++;
  }

  String token = _strtokState!.substring(start, end);

  // Save remaining state
  if (end < _strtokState!.length) {
    // Find the next non-delimiter or just save from end.
    // C strtok replaces the delimiter with \0 and advances the pointer.
    // So the next strtok continues from end+1. But if end+1 is a delimiter,
    // the next strtok call will skip it.
    _strtokState = _strtokState!.substring(end + 1);
  } else {
    _strtokState = null;
  }

  return token;
}