- 论坛徽章:
- 0
|
代码如下://从键盘上读取任意长度的一段文本,确定该文本中每个单词的出现频率(忽略大小写),
//该段文本的长度不完全是任意的,因为我们要给成学中数组大小指定一个限制,
//但可以使该数组存储任意大小的文本
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>
#define TEXTLEN 10000
#define BUFFERSIZE 100
#define MAXWORDS 500
#define WORDLEN 15
int main(void)
{
char text[TEXTLEN+1];
char buffer[BUFFERSIZE];
char endstr[] = "*\n";
const char space = ' ';
const char quote = '\'';
char words[MAXWORDS][WORDLEN+1];
int nword[MAXWORDS];//nword存储words数组中各个单词出现次数
char word[WORDLEN+1];
int wordlen = 0;
int wordcount = 0;
int i = 0;
int index = 0;
bool isnew = true;
printf("enter text on an arbitrary number of lines.");
printf("\nenter a line containing just an asterisk to end input:\n\n");
while(true)
{
if(!strcmp(fgets(buffer,BUFFERSIZE,stdin),endstr));//从文件读取一个字符串
break;
if(strlen(text)+strlen(buffer)+1>TEXTLEN)
{
printf("Maximum capacity for text exceeded.Terminating program.");
return 1;
}
strcat(text,buffer);//将字符串buffer连接到字符串text后面
}
for(i = 0;i<strlen(text);i++)
{
if (text == quote || isalnum(text) )
//isalnum()当参数是数字或字母的时候返回非0值,其他是0
continue;
text = space ;
}
while(true)
{
while(text[index]==space)
++index;
if(text[index]=='\0')
break;
wordlen = 0;
while(text[index]==quote||isalpha(text[index]))
{
if(wordlen == WORDLEN)
{
printf("maximum word length exceede. terminating program.");
return 1;
}
word[wordlen++] = tolower(text[index++]);
}
word[wordlen] = '\0';
for(i = 0;i < wordcount;i++)
if(strcmp(word,words) == 0)
{
++ nword;
isnew = false;
break;
}
if(isnew)
{
if(wordcount >= MAXWORDS)
{
printf("\n maximum word count exceeded. terminating proqram.");
return 1;
}
strcpy(words[wordcount],word);
nword[wordcount++] = 1;
}
}
for(i = 0;i < wordcount;i++)
{
if (!(i%3))
printf("\n");
printf("%-15s%5d",words,nword);
}
return 0;
}
我的编译器是C-free,是不是与编译器也有关呀?
麻烦大家啦。。我昨天看了一晚上啦。。实在不知道怎么改啦。。。 |
|