c语言程序设计题(急!) 20
编写一个程序,其功能是将用户输入的一段英文(注意包含空格,逗号,句号及英文字母)分离出单词,并以每个单词出现的次数从高到低输出单词及其次数,次数相同的单词一起对应字符串大...
编写一个程序,其功能是将用户输入的一段英文(注意包含空格,逗号,句号及英文字母)分离出单词,并以每个单词出现的次数从高到低输出单词及其次数,次数相同的单词一起对应字符串大小升序输出。
例如:Green is on the left,red is on the right, the right is afraid of water, the left is afraid of insects.
输出:is(4) the(4) afraid(2) left(2) of(2) on(2) right (2) Green(1) insects(1) red(1) water(1) 展开
例如:Green is on the left,red is on the right, the right is afraid of water, the left is afraid of insects.
输出:is(4) the(4) afraid(2) left(2) of(2) on(2) right (2) Green(1) insects(1) red(1) water(1) 展开
2009-12-30
展开全部
英文输入完成后,用CTRL+Z输入结束标志。
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_MAX (80)/*单个单词的最大长度*/
typedef struct {
char word[STR_MAX];
int count;
} node;
int ref(node * const ws,const int n,const char * const word)
{
int i;
for (i = 0; i<n; i++) {
if (strcmp(ws[i].word,word)==0) {
ws[i].count++;
return 1;
}
}
return 0;
}
node *input(int * const n)
{
node *ws=NULL;
char word[STR_MAX];
*n=0;
while (scanf("%*[^a-zA-Z]%[a-zA-Z]%*c",word)!=EOF)
{
if (!ws) {
ws=malloc(sizeof(node));
ws[*n].count=1;
strcpy(ws[(*n)++].word,word);
}
else if (!ref(ws,*n,word)){
ws=realloc(ws,sizeof(node)*(*n+1));
strcpy(ws[(*n)].word,word);
ws[(*n)++].count=1;
}
}
return ws;
}
int comp(const void *a,const void *b)
{
return (*(node *)b).count-(*(node *)a).count;
}
int main(void)
{
node *words=NULL;
int i,n=0;
words=input(&n);
qsort(words,n,sizeof(node),comp);
for (i = 0; i<n; i++) {
printf("%s(%d)\n",words[i].word,words[i].count);
}
return 0;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_MAX (80)/*单个单词的最大长度*/
typedef struct {
char word[STR_MAX];
int count;
} node;
int ref(node * const ws,const int n,const char * const word)
{
int i;
for (i = 0; i<n; i++) {
if (strcmp(ws[i].word,word)==0) {
ws[i].count++;
return 1;
}
}
return 0;
}
node *input(int * const n)
{
node *ws=NULL;
char word[STR_MAX];
*n=0;
while (scanf("%*[^a-zA-Z]%[a-zA-Z]%*c",word)!=EOF)
{
if (!ws) {
ws=malloc(sizeof(node));
ws[*n].count=1;
strcpy(ws[(*n)++].word,word);
}
else if (!ref(ws,*n,word)){
ws=realloc(ws,sizeof(node)*(*n+1));
strcpy(ws[(*n)].word,word);
ws[(*n)++].count=1;
}
}
return ws;
}
int comp(const void *a,const void *b)
{
return (*(node *)b).count-(*(node *)a).count;
}
int main(void)
{
node *words=NULL;
int i,n=0;
words=input(&n);
qsort(words,n,sizeof(node),comp);
for (i = 0; i<n; i++) {
printf("%s(%d)\n",words[i].word,words[i].count);
}
return 0;
}
//---------------------------------------------------------------------------
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询