Search code examples
cc-stringsturbo-c

strstr to find a word in a string using c returning true all the time


Good Day,

So I decided to go trough my C again and started making a simple search the word in a string.

Here is my code:

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

main(){
char word[100];
char sentence[100];

clrscr();
printf("Enter a word: ");
fgets(word, 100, stdin);
getch();
printf("The word is : %s", &word);
getch();
printf("\nEnter a sentence: ");
fgets(sentence, 100, stdin);
getch();
printf("The sentence is: %s",&sentence);
getch();
if(strstr(sentence,word) == 0){
  printf("word found!");
}
getch();
return 0;
}

The problem now is that whenever i try to search for the word in a string using strstr, it always returns word found. I also tried using strcmp but that will only compare the first instance of the string and stops when a match is not found so its not really advisable if you want to do a word searching in a string problem.

I haven't really made a program like this before, never needed one actually. So may I ask why is not working properly since according to its description strstr should be to search for a word in a sentence or did I just misunderstood it.

Also if you have any comments on my program feel free to say so, so that I may become aware of my mistake.

Thank you

Example: word: dog
sentence: the dog is here
should return true


Solution

  • This line

    if(strstr(sentence,word) == 0)
    

    should be

    if(strstr(sentence,word) != NULL)
    

    strstr() returns a pointer to the first occurence of word in sentence or NULL if the word was not found.

    For details please read here.


    Also using fgets() to read in the "strings" appends a '\n' to the end of the "strings". This prohibits successful comparsion.

    To chop of the trailing '\n' you could do like this:

    fgets(word, sizeof(word), stdin);
    {
      size_t size = strlen(word);
    
      if (size && ('\n' == word[size-1]))
      {
        word[size-1] = '\0';
      }
    }