69,373
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<string.h>
#include <ctype.h>
struct WORD
{
char wordname[10];
int wordcount;
};
int statistics (char * source,struct WORD words[]);
void sortWords(struct WORD words[],int len);
void printWords(struct WORD words[],int len);
int main(void)
{
struct WORD words[200];
char sentence[2000];
int len;
char * source=sentence;
printf("Please enter a sentence:\n");
gets(sentence);
len=statistics (source,words);
sortWords(words,len);
printWords(words,len);
return 0;
}
int statistics (char * source,struct WORD words[])
{
char temp[10];
int len=0,i=0;
while(*source!='\0')
{
if((*source>='a'&&*source<='z') || (*source>='A'&&*source<='Z') )//----
{
temp[i]=tolower(*source);//--
i++;
}
else
{
temp[i]='\0';
i = 0;
for(int j=0;j <= len;j++)
{
if( len == 0 )
{
strcpy(words[0].wordname,temp);
words[0].wordcount = 1;
len++;
break;
}
if( strcmp(words[j].wordname,temp)==0 )
{
words[j].wordcount++;
break;
}
else
{
if( j == len )
{
strcpy(words[j].wordname,temp);
words[j].wordcount = 1;
len++;
break;
}
}
}
}
source++;
}
return len;
}
void sortWords(struct WORD words[],int len)
{
int i,j;
struct WORD t;
for(i=0;i<len-1;i++)
{
for(j=i+1;j<len;j++)
{
if( words[i].wordcount < words[j].wordcount )
{
t=words[i];
words[i]=words[j];
words[j]=t;
}
else if( words[i].wordcount == words[j].wordcount )
{
if( strcmp(words[i].wordname, words[j].wordname) > 0 )
{
t=words[i];
words[i]=words[j];
words[j]=t;
}
}
}
}
}
void printWords(struct WORD words[],int len)
{
int i;
printf("The result is as follows:\n");
for(i=0;i<len;i++)
printf("%s %d\n",words[i].wordname,words[i].wordcount);
}