C语言编程:从键盘中输入一个英文字符串

从键盘中输入一个英文字符串,以‘#’作为结束标志,编程统计字符串中英文单词的个数,并按单词出现频次升序排序显示每个单词出现的次数

#include<stdio.h>

#include<stdlib.h>


int main()

{

int strSize = 100;

char *str = (char *)malloc(sizeof(char) * strSize);

int charNum = 0;

char input;

//逐个字符输入字符串,可以输入int可以表示的最大值个字符

printf("请输入任意个字符:\n");

while(true)

{

scanf("%c",&input);

if(input != '#')

{

if((input >= 'A' && input <= 'Z') || (input >= 'a' && input <= 'z'))

{

if(charNum > strSize)

{

strSize += 100;

str = (char *)realloc(str,strSize);

}

str[charNum] = input;

charNum++;

}

}

else

{

break;

}

}

//输入结果分析

int i = 0,j = 0;

char *tempChar = (char *)malloc(sizeof(char) * charNum);

int *tempCharNum = (int *)malloc(sizeof(int) * charNum);

int charType = 0;

bool exist = false;

for(i = 0; i < charNum; i++)

{

exist = false;

tempChar[i] = '#';

tempCharNum[i] = 0;

for(j = 0; j < charNum; j++)

{

if(tempChar[j] == '#')

{

break;

}

if(tempChar[j] == str[i])

{

exist = true;

tempCharNum[j] += 1;

}

}

if(exist == false)

{

tempChar[charType] = str[i];

tempCharNum[charType] = 1;

charType++;

}

}

int t1;

char t2;

for(j = 0; j < charType - 1; j++)

{

for(i = 0; i < charType; i++)


if(tempCharNum[i] > tempCharNum[i+1])//如果a[i]大于a[i+1]

{

//交换a[i]和a[i+1]的值,即把较大的元素往后排

t1 = tempCharNum[i];

tempCharNum[i] = tempCharNum[i+1];

tempCharNum[i+1] = t1;


t2 = tempChar[i];

tempChar[i] = tempChar[i+1];

tempChar[i+1] = t2;

}

}

for(i = 0; i < charNum; i++)

{

if(tempChar[i] != '#')

{

printf("单词:%c,次数:%d\n",tempChar[i],tempCharNum[i]);

}

}

free(str);

free(tempChar);

free(tempCharNum);

return 0;

}


温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-11-18
#include "stdio.h"
main()
{
 char s[81],c;
 int i,num=0,word=0;
 printf("请输入一行英文:\n");
 gets(s);
 for(i=0;(c=s[i])!='#';i++)  //遇到#结束 
 if(c==' ') word=0;
  else if(word==0)
    {
      word=1;
      num++;
    }
 printf("本行中共有%d个单词.\n",num);
}

第2个回答  2013-11-18
gets读入,
计算长度
对于每个字符,如果是字母就记单词开始,当遇到空白和#就是单词结束,单词结束时,计数+1,单词对应的个数加1,
最后排序
第3个回答  2013-11-18
到底是单词还是字母?
相似回答