Check substring exists in a string in C

none picture none · Oct 8, 2012 · Viewed 471.9k times · Source

I'm trying to check whether a string contains a substring in C like:

char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
    /* .. */
}

What is something to use instead of string::find in C++?

Answer

nneonneo picture nneonneo · Oct 8, 2012
if(strstr(sent, word) != NULL) {
    /* ... */
}

Note that strstr returns a pointer to the start of the word in sent if the word word is found.