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"
Asked
Active
Viewed 94 times
0

trezurka
- 9
- 2
-
3find "cat" verify that the character before (if it exists) is whitespace **and** that the character afterwards (if ir exists) is whitespace... so "scatter" fails. – pmg Dec 07 '21 at 12:36
-
1C have [some nice functions](https://en.cppreference.com/w/c/string/byte#String_examination) to examine strings. I'm sure one of them could be used for the first part mentioned in the comment by @pmg ('find "cat"'). – Some programmer dude Dec 07 '21 at 12:39
-
1. Use strstr 2. check for trailing white space. Or alternatively split up the data with strtok or similar first. All of this ought to be found in the chapter called strings in your C book. – Lundin Dec 07 '21 at 12:59
-
Is [this](https://stackoverflow.com/questions/42352846/matching-an-exact-word-using-in-c) the same question as yours? – Ahmed Khaled Dec 07 '21 at 13:07
1 Answers
1
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;
}

CaptainHb
- 13
- 4