Reputation: 9
How to find exact words in string in C?
Example:
word to find: "cat"
string: "cats dog" result nothing
string "cat dog" result found word "cat"
Upvotes: 0
Views: 230
Reputation: 13
first you can use strtok function to split string into separate word and then use strcmp to comapre the result words againts your interest word.
#include <stdio.h>
#include <string.h>
int main() {
char string[50] = "cats dog";
char *token = strtok(string, " "); // split string by space
// here token contains one word in string
// each time strtok(NULL, " ") is called, the next word will be extracted
while( token != NULL ) {
printf( " %s\n", token ); //printing each token
if (!strcmp(token, "cat"))
{
printf("cat found!\n");
}
token = strtok(NULL, " ");
}
return 0;
}
Upvotes: 1