countOccurrences method
Counts non-overlapping occurrences of substring in this string.
Returns 0 when substring is empty. Matches are consumed left to right,
so overlaps are not double-counted.
Example:
'aaaa'.countOccurrences('aa'); // 2
Implementation
int countOccurrences(String substring) {
if (substring.isEmpty) return 0;
int count = 0;
int i = 0;
while (true) {
i = indexOf(substring, i);
if (i == -1) break;
count++;
i += substring.length;
}
return count;
}