要求:输入一个字符串,统计每个单词的个数。单词间用空格隔开,可多个空格,写出自己认为高效的算法。
例如:输入:I love love China
输出为:
I: 1
love: 2
China: 1
#include <stdio.h>
#include<iostream>
#include <string>
struct struct_words
{
char word[20];
int count;
};
int main() {
char string[100];
char c;
struct_words words[20];
int i = 0, k = 0, ws = 0;
for (; i < 20; i++) { //初始化结构体
words[i].word[0] = '\0';
words[i].count = 0;
}
puts("please input words.");
gets_s(string);
puts("=============开始取词================");
i = 0;
do {
c = string[i];
if (c != ' ' && c != '\0') {
words[k].word[ws] = c;
words[k].count = 1;
ws++;
}
else {
words[k].word[ws] = '\0';
ws = 0;
k++;
}
i++;
} while (c != '\0');
puts("=========== 合并相同的单词 ==============");
for (i = 0; words[i].word[0] != '\0'; i++) {
for (k = i; words[k].word[0] != '\0'; k++) {
if (strcmp(words[i].word, words[k].word) == 0
&& words[k].count == 1) {
words[k].count--;
words[i].count++;
}
}
}
puts("=============== End ==============");
for (i = 0; words[i].word[0] != '\0'; i++) {
if (words[i].count != 0)
printf("%s:\t\t%d\n", words[i].word, words[i].count);
}
system("pause");
return(0);
}