allIndicesOf method

List<int> allIndicesOf(
  1. String substring
)

Returns all start indices where substring occurs (non-overlapping). Audited: 2026-06-12 11:26 EDT

Implementation

List<int> allIndicesOf(String substring) {
  // An empty needle has no well-defined positions, so report none.
  if (substring.isEmpty) return <int>[];
  // Pre-size to the maximum possible non-overlapping match count (string length
  // divided by needle length, plus one slack) to fill a fixed list rather than
  // grow it; the trailing sublist trims the unused tail. The `> 0 ? : 1` is a
  // defensive guard against division by zero even though the empty case already
  // returned above.
  final int maxOccurrences = length ~/ (substring.length > 0 ? substring.length : 1) + 1;
  final List<int> out = List<int>.filled(maxOccurrences, 0);
  int i = 0;
  int idx = 0;
  // Advance past each match by the needle length so overlapping matches are not
  // counted twice (e.g. "aa" in "aaaa" reports indices 0 and 2, not 0,1,2).
  while (true) {
    i = indexOf(substring, i);
    if (i == -1) break;
    out[idx++] = i;
    i += substring.length;
  }
  return out.sublist(0, idx);
}