标题
单词统计
描述
输入字符串string[N](N≤100),各个单词以空格隔开,单词长度小于等于8,输入单词word[M](M≤8),在string中查找出相同的单词并统计该单词出现的次数信息,输出单词和出现次数的信息, 数据之间空一格空格。主函数输入字符串和待统计单词,编写函数count()实现统计和信息输出。
时间限制
1
内存限制
10000
类别
1
输入说明
输入一行字符以空格隔开各个单词,输入要统计的单词。
输出说明
格式输出:输出单词及其出现的次数信息,数据之间空一格。
输入样例
dog cat dog dog the abc dog hahe
dog
输出样例
dog 4
提示
采用重循环结构实现计算过程,输出数据之间空一格。
我的想法是将每一个单词都存到数组里面去,然后再对每一项进行检索(利用strcmp)函数
#include <stdio.h>
#include <string.h>
int main() {
char str[20][100], word[8];
int i = 0;
do {
scanf("%s", str[i]);
i++;
} while (getchar() != '\n');//每遇到一个空格就保存一个单词
gets(word);
void count(char str[][100], char s[], int n);
count(str, word, i);
}
void count(char str[][100], char s[], int n) {
int sum = 0, len2 = strlen(s);
for (int i = 0; i < n; i++) {
if (strcmp(str[i], s) == 0)//用strcmp函数比较是否是需要查找的字符串
sum++;
}
printf("%s", s);
printf(" %d", sum);
}