c count occurrences of a substring

Solutions on MaxInterview for c count occurrences of a substring by the best coders in the world

showing results for - "c count occurrences of a substring"
Sarah
01 Nov 2020
1#include <stdio.h>
2#include <string.h>
3 
4int count(const char *str, const char *sub) {
5    int sublen = strlen(sub);
6    if (sublen == 0) return 0;
7    int res = 0;
8    for (str = strstr(str, sub); str; str = strstr(str + sublen, sub))
9        ++res;
10    return res;
11}
12 
13int main() {
14        printf("%d\n", count("sea shells sea shells on the sea shore", "sea"));
15}