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?
The results can be different depending whether you allow an overlap or not:
Output
You could do something like
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.
USE KMP and you can do it in O(n)
You can see wiki pages for details
Should already processed parts of the string should be consumed or not?
For example, what's the expect answer for case of searching
oo
infoooo
, 2 or 3?If the latter (we allow substring overlapping, and the answer is three), then Joachim Isaksson suggested the right code.
If we search for distinct substrings (the answer should be two), then see the code below (and online example here):