C count occurrences of a substring code example
Example: C count occurrences of a substring
#include <stdio.h>
#include <string.h>
int count(const char *str, const char *sub) {
int sublen = strlen(sub);
if (sublen == 0) return 0;
int res = 0;
for (str = strstr(str, sub); str; str = strstr(str + sublen, sub))
++res;
return res;
}
int main() {
printf("%d\n", count("sea shells sea shells on the sea shore", "sea"));
}