请问怎么统计指定单词的个数
eg:输入两行
cat cat dog
dog dog cat
统计cat的个数
谢!
1条回答 默认 最新
ChatGPTᴼᴾᴱᴺᴬᴵ 2022-12-26 12:26关注在 C 语言中,您可以使用以下方法来统计指定单词的个数:
1.使用字符串函数 strstr,该函数会在一个字符串中搜索另一个字符串的出现位置。您可以使用这个函数来搜索单词,并使用一个计数器来统计单词出现的次数。
例如:
#include <stdio.h> #include <string.h> int main() { char s[100]; int count = 0; while (fgets(s, 100, stdin)) { // 在字符串 s 中搜索单词 "cat" char *p = strstr(s, "cat"); while (p) { // 如果找到了,计数器加 1 count++; // 继续在剩余的字符串中搜索 p = strstr(p + 1, "cat"); } } printf("%d\n", count); return 0; }2.使用 strtok 函数,该函数会将字符串按照指定的分隔符分割成若干个令牌(token)。您可以使用这个函数来将字符串分割成单词,然后遍历每个单词,如果找到了要统计的单词,计数器加 1。
例如:#include <stdio.h> #include <string.h> int main() { char s[100]; int count = 0; while (fgets(s, 100, stdin)) { // 将字符串 s 分割成若干个令牌 char *word = strtok(s, " \t\n"); while (word) { // 比较当前令牌是否是要统计的单词 if (strcmp(word, "cat") == 0) { // 如果是,计数器加 1 count++; } // 继续分割字符串,获取下一个令牌 word = strtok(NULL, " \t\n"); } } printf("%d\n", count); return 0; }这两种方法都可以用来统计指定单词的个数,您可以根据自己的需要选择合适的方法。
解决 无用评论 打赏 举报