Home > Software engineering >  How should I use strcmp() to check whether a string is found in a larger string?
How should I use strcmp() to check whether a string is found in a larger string?

Time:12-13

The problem is pretty simple. I have to check whether a string is a substring of a string or not.

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

int main() {
    char *a = "Aristotle was not a good a philosopher";
    int i = 1;
    if (strcmp(a, "good") < 0) {
          return i;
    }
    return 0;
}

CodePudding user response:

There is no great sense to use the function strcmp. Instead you should use the function strstr.

return strstr( a, "good" ) != NULL;

or

return strstr( a, "good" ) == NULL;

depending on what you are going to return if the string "good" is present in the string a or not.

CodePudding user response:

as Vlad from Moscow answered the correct way is to use strstr

if you need for some (unknown) reason to use strcmp then your code need a loop (also note that strcmp return 0 in case the strings are the same)

something like the below (note there are no sanity checks below to check for example if the subset_string is shorter or longer then the original stream etc ..)

int main() {
char *a = "Aristotle was not a good a philosopher";
char *word_to_find = "good";
for(int i=0;i< (strlen(a)-strlen(word_to_find));i  ) 
{
 if (strcmp((a i), b) == 0) {
      return 0;
}
return 1;

}

  • Related