Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
Jordan Borisov Avatar asked Jan 29 '12 10:01

Jordan Borisov


People also ask

How do you count a substring in a string in python?

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.

How many Substrings a string can have?

Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.


2 Answers

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.

like image 82
Joachim Isaksson Avatar answered Oct 22 '22 19:10

Joachim Isaksson


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++;
        }
    
like image 34
Eldar Abusalimov Avatar answered Oct 22 '22 18:10

Eldar Abusalimov