我正在尝试计算字符串中出现的单词。对于字符串 S,我需要显示每个单词以及该单词在字符串中出现的次数。
示例:
string = ";! one two, tree foor one two !:;"
结果:
one: 2
two: 2
tree: 1
foor: 1
这是我的代码,但它没有返回正确的计数:
#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);
};
它回来了:
one : 1
two : 0
tree : 0
foor : 0
one : 1
two : 0
: : 0