统计单词出现次数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct word
{
int num;
char str[50];
};
int Compare(const void *a,const void *b)
{
return strcmp((char*)a, (char *)b);
}
int main()
{
struct word word[20];
int i = 0, j = 0;
while (1)
{
char a = getchar();
if (a >= 'A'&&a <= 'Z')
{
a = a - 'A' + 'a';
}
if (a != ' '&&a != ','&&a != '.'&&a != '\n')
{
word[i].num = 1;
word[i].str[j] = a;
j++;
word[i].str[j] = '\0';
}
else if(a!='\n')
{
i++;
j = 0;
word[i].num = 0;
word[i].str[j] = '\0';
}
else
{
break;
}
}
qsort(word, i + 1, sizeof(word[0]), Compare);
for (int ii = 0; ii < i+1; ii++) {
if (strcmp(word[ii].str, word[ii + 1].str) == 0) {
word[ii + 1].num = word[ii].num + 1;
word[ii].num = 0;
}
}
for (int ii = 0; ii < i+1; ii++) {
if (word[ii].num != 0 && word[ii].str[0] != '\0')
printf("%s:%d\n", word[ii].str, word[ii].num);
}
}