-
Count words in a string
Hello,
I'm looking for a way to count a specific word in a string, here's an example of what I've written
Code:
char TextString[]="hello this is a test string, used used used to count specific words";
char *StringToSearch[3]={"this","a", "used"};
int this_count=0, a_count=0, used_count=0;
So I want to put in a loop and look for these words, I was thinking of using strstr function, but that just looks the strings once.
Do you have a solution?
-
Have a moving pointer so you can search the rest of the string after you find a match. Something like:
Code:
char *str, *match;
int count = 0;
for(str = TextString;str;str = match == null ? match : match + strlen(StringToSearch[index]))
if((match = strstr(str, StringToSearch[index])))
count++;