-1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
sorcene
  • 11
  • 1
  • use stktok(), put results in an array, then check if the word matches any words in the array – OldProgrammer Oct 25 '21 at 21:15
  • 3
    alternatively `strstr()` returns a pointer to the start of the match, so checking what comes before and after is easy from that point on. –  Oct 25 '21 at 21:15
  • [Like this](https://www.google.com/search?q=How+do+I+check+if+a+word+is+in+sentence+on+C) – Marco Bonelli Oct 25 '21 at 21:16
  • Does this answer your question? [Check substring exists in a string in C](https://stackoverflow.com/questions/12784766/check-substring-exists-in-a-string-in-c) – skrrgwasme Oct 25 '21 at 21:23
  • Yeah, I saw that, couldn't find a solution there. I ll try to implement @Frank suggestion – sorcene Oct 25 '21 at 21:29

1 Answers1

1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335