I’m trying to count words occurrence in a string. For a string S, I need to show each word and how many times this word is present in the string.
Exemple:
string = ";! one two, tree foor one two !:;"
Result:
one: 2
two: 2
tree: 1
foor: 1
Here is my code but it’s not returning the right count:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count_word(char * mot, char * text) {
int n = 0;
char *p;
p = strstr(text, mot);
while (p != NULL) {
n++;
p = strstr(p + 1, mot);
}
return n;
}
void show_all_words(char * text) {
char * p = strtok(text, " .,;-!?");
while (p != NULL) {
printf ("%s : %d\n", p, count_word(p, text));
p = strtok(NULL, " .,;-!?");
}
}
int main(char *argv[]) {
char text[] = ";! one two, tree foor one two !:;";
show_all_words(&text);
return (EXIT_SUCCESS);
};
it’s returning:
one : 1
two : 0
tree : 0
foor : 0
one : 1
two : 0
: : 0
The function
strtokchanges its parameter. You can fix the problem by duplicating the string, callingstrtokon one copy andcount_wordon the other.Also, take a precaution not to output the count for the same word twice.