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?
Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string. Parameters: The count() function has one compulsory and two optional parameters.
Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.
You could do something like
int count = 0;
const char *tmp = myString;
while(tmp = strstr(tmp, string2find))
{
count++;
tmp++;
}
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.
Should already processed parts of the string should be consumed or not?
For example, what's the expect answer for case of searching oo
in foooo
, 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):
char *str = "This is a simple string";
char *what = "is";
int what_len = strlen(what);
int count = 0;
char *where = str;
if (what_len)
while ((where = strstr(where, what))) {
where += what_len;
count++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With