Search code examples
cstringsearchsubstring

find the count of substring in string


I have to find the count of a substring in a string using the C language. I'm using the function strstr but it only finds the first occurrence.

My idea of the algorithm is something like searching in the string while strstr does not return null and to substring the main string on each loop. My question is how to do that?


Solution

  • You could do something like

    int countString(const char *haystack, const char *needle){
        int count = 0;
        const char *tmp = haystack;
        while(tmp = strstr(tmp, needle))
        {
            count++;
            tmp++;
        }
        return count;
    }
    

    That is, when you get a result, start searching again at the next position of the string.

    strstr() doesn't only work starting from the beginning of a string but from any position.