这题描述错了。。不是按照次数降序,而是单词升序。。。
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
typedef struct{
char word[20];
int cnt;
}Word;
int cpr(const void * a,const void* b)
{
Word * x = (Word *) a;
Word * y = (Word *) b;
return strcmp(x->word,y->word);
}
int main()
{
char str[1000];
char temp[20];
Word w[1000];
int i,j = 0,k = 0,l = 0;
int flag = 0;//1表示单词存在于字典中,0表示是新单词
gets(str);
for(i = 0;i<strlen(str);i++)
{
if(isalpha(str[i])) // 是字母
temp[j++] = tolower(str[i]);
else if(str[i] == ' ' || str[i] == ',' || str[i] == '.') //单词结束
{
temp[j] = '\0';
j = 0;
flag = 0;
if(temp[0]!='\0')//非空单词
{
for(k = 0;k<l;k++) // 比较单词是否在字典中
{
if(!strcmp(w[k].word,temp)) // 在字典中
{
w[k].cnt++;
flag = 1;
break;
}
}
if(!flag) // 不在字典中
{
strcpy(w[l].word,temp);
w[l].cnt = 1;
l++;
}
}
else
continue;
}
else // 其他字符
temp[j++] = str[i];
}
qsort(w,l,sizeof(w[0]),cpr);
for(i = 0;i<l;i++)
printf("%s:%d\n",w[i].word,w[i].cnt);
return 0;
}

京公网安备 11010502036488号