cloopsif-statementc-stringsstrstr

How to count how many word in string?


I want to know how to count how many words are in a string. I use strstr to compare and it works but only works for one time

like this

char buff = "This is a real-life, or this is just fantasy";
char op = "is";

if (strstr(buff,op)){
    count++;
}
printf("%d",count);

and the output is 1 but there are two "is" in the sentence, please tell me.


Solution

  • For starters you have to write the declarations at least like

    char buff[] = "This is a real-life, or this is just fantasy";
    const char *op = "is";
    

    Also if you need to count words you have to check whether words are separated by white spaces.

    You can do the task the following way

    #include <string.h>
    #include <stdio.h>
    #include <ctype.h>
    
    //...
    
    size_t n = strlen( op );
    for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p += n )
    {
        if ( p == buff || isblank( ( unsigned char )p[-1] ) )
        {
            if ( p[n] == '\0' || isblank( ( unsigned char )p[n] ) )
            {
                count++;
            }
        }
    }
    printf("%d",count);
    

    Here is a demonstration program.

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    int main(void) 
    {
        char buff[] = "This is a real-life, or this is just fantasy";
        const char *op = "is";
        size_t n = strlen( op );
    
        size_t count = 0;
    
        for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p += n )
        {
            if ( p == buff || isblank( ( unsigned char )p[-1] ) )
            {
                if ( p[n] == '\0' || isblank( ( unsigned char )p[n] ) )
                {
                    count++;
                }
            }
        }
    
        printf( "The word \"%s\" is encountered %zu time(s).\n", op, count );
    
        return 0;
    }
    

    The program output is

    The word "is" is encountered 2 time(s).