Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #82 Count substring occurrences

Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.

import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(s, t);

This uses the Apache Commons Lang library.
import static java.util.regex.Pattern.compile;
import static java.util.regex.Pattern.quote;
import java.util.regex.Matcher;
int z = 0;
Matcher m = compile(quote(t)).matcher(s);
while (m.find()) ++z;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern pattern = Pattern.compile(Pattern.quote(t));
Matcher matcher = pattern.matcher(s);
int count = 0;
while(matcher.find()) count++;

Overlapping occurrences are not counted.
import static java.util.regex.Pattern.compile;
import static java.util.regex.Pattern.quote;
import java.util.regex.Matcher;
int z, i = z = 0;
Matcher m = compile(quote(t)).matcher(s);
while (m.find(i)) {
    ++z;
    i = m.start() + 1;
}

This will count overlapped values.
#include <string.h>
unsigned n;
for (n = 0; s = strstr(s, t); ++n, ++s)
	;

Overlapping occurrences are counted.
This destroys the pointer s.

New implementation...
< >
deleplace