闲来无事,写一段吧:
//假定,空格为唯一分隔符,回车表示完成输入
//以一个数组countArray来记录wordcount,用它的索引来表示wordlength
//wordlen = index + 1
#include
#include
#include
#define MAX_WORD_LENGTH 30
unsigned int countArray[MAX_WORD_LENGTH];
void Initialize();
void OutPut();
void main(void)
{
char input;
unsigned int currentLength = 0;
Initialize();
printf("Please enter your words:\n");
for(input = getchar();;input = getchar())
{
if(input != ' ' && input != '\n')
currentLength++;
else
{
if(currentLength == 0);
else if(currentLength > MAX_WORD_LENGTH)
{
printf("Input string error, length of word exceeds length limit!\n");
exit(0);
}
else//0 < length <= MAX_WORD_LENGTH
{
countArray[currentLength - 1]++;
currentLength = 0;
}
if(input == '\n')break;
}
}
OutPut();
}
void Initialize()
{
int i;
for(i = 0;i < MAX_WORD_LENGTH;i++)
countArray[i] = 0;
}
void OutPut()
{
unsigned int i,maxLen = 0,maxCount = 0;
printf("WordLen\tWordCount\n");
for(i = 0;i < MAX_WORD_LENGTH;i++)
{
if(countArray[i] != 0)
{
printf("%d\t%d\n",i + 1,countArray[i]);
maxLen = i + 1;
if(maxCount < countArray[i]) maxCount = countArray[i];
}
}
printf("MaxLen = %d, MaxCount = %d\n",maxLen,maxCount);
}