简体   繁体   中英

How do I check if a word is in sentence on C

For example: str = "I have a meeting" word = "meet" should give 0 since there is no such word

I tried strstr(str, word) but it checks for substring, so it gives 1 for this example

I assume that words are sequences of characters separated by blank characters.

You can use the function strstr but you need also to check that blanks precede and follow the found substring or that the returned pointer points to the beginning of the sentence or the found substring forms the tail of the sentence.

Here is a demonstration program that shows how such a function can be defined.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char * is_word_present( const char *sentence, const char *word )
{
    const char *p = NULL;
    
    size_t n = strlen( word );
    
    if ( n != 0 )
    {
        p = sentence;
    
        while ( ( p = strstr( p, word ) ) != NULL )
        {
            if ( ( p == sentence || isblank( ( unsigned char )p[-1] ) ) &&
                 ( p[n] == '\0'  || isblank( ( unsigned char )p[n]  ) ) )
            {
                break;
            }
            else
            {
                p += n;
            }
        }
    }
    
    return ( char * )p;
}

int main( void )
{
    char *p = is_word_present( "I have a meeting", "meet" );
    
    if ( p )
    {
        puts( "The word is present in the sentence" );
    }
    else
    {
        puts( "The word is not present in the sentence" );
    }
    
    p = is_word_present( "I meet you every day", "meet" );
    
    if ( p )
    {
        puts( "The word is present in the sentence" );
    }
    else
    {
        puts( "The word is not present in the sentence" );
    }
    

    return 0;
}

The program output is

The word is not present in the sentence
The word is present in the sentence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM