程序采用的是自顶而下的过程式编程,用动态数组来存储单词。对于字符串的读取则是采用一个一个的从文件中读取出来,并且同时对他们进行判断,看是否是字母、‘-’、‘'‘;如果是则存储在字符串中,如果遇到不是,则加入字符串结束符并且对整个字符串进行处理。对于字符串的查找和插入,则采用的是二分查找和顺序插入的算法;最后利用选择排序,选出最多的15个,并输出到文件中去。
//一下是程序代码
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "ctype.h"
typedef struct //存放一个单词,和他的个数
{
char str[25];
int num;
}Str;
Str *word;
int Look(Str word1,int n) //利用二分查找法
{
int start=1,end=n-1,mid;
if(n==1) return 1;
while(start<=end)
{
mid=(start+end)/2;
if(strcmp(word1.str,word[mid].str)==0)
{
word[mid].num++;
return 0;
}
if(strcmp(word1.str,word[mid].str)>0)
end=mid-1;
else start=mid+1;
}
return 1;
}
int Hsort(Str word1,int n) //排序插入
{
if(n==1)
{
strcpy(word[1].str,word1.str);
word[1].num=word1.num;
return 0;
}
int i;
for(i=n-1;i>=1 && strcmp(word1.str,word[i].str)>=0;i--) //数组往后移动
{
strcpy(word[i+1].str,word[i].str);
word[i+1].num=word[i].num;
}
strcpy(word[i+1].str,word1.str); //插入
word[i+1].num=word1.num;
return i+1;
}
void Isort(int n) //利用选择排序找最多的15个
{
int i,j,max;
Str ss;
for(i=1;i<17;i++) //找16个最大的
{
max=i; //找第i个最大的
for(j=i+1;j<=n;j++)
if(word[j].num>word[max].num) max=j;
ss=word[max]; //交换
word[max]=word[i];
word[i]=ss;
}
}
void main()
{
FILE *fin;
char c;
Str word1;
int strlen,Maxlen,count,i;
Maxlen=50;
strlen=0;
count=1;
fin=fopen("c:\\a.txt","r"); //打开需要统计的文章,例:C盘下的a.txt文档
word=(Str *)malloc(sizeof(Str)*(50)); //初始分配50个Str空间
while((c=fgetc(fin))!=EOF)
{
if( isalpha(c) || c=='\'' || c=='-') word1.str[strlen++]=c;
while((c=fgetc(fin))!=EOF && ( isalpha(c) || c=='\'' || c=='-'))
word1.str[strlen++]=c;
word1.str[strlen]='\0';
word1.num=1;
if(count>=Maxlen) //检查空间是否足够,不足则加
{
word=(Str *)realloc(word,Maxlen+10);
Maxlen+=10;
}
if(Look(word1,count) && strlen>0) //对字符串进行处理
{
int t;
t=Hsort(word1,count);
count++;
}
strlen=0;
}
fclose(fin);
Isort(count); //对字符串排序
fin=fopen("C:\\b.txt","w"); //打开输出文件 文件路径可以改,但要注意'\'
fprintf(fin,"The top 15th words:\n");
for(i=1;i<16;i++) //输出15个最大的
fprintf(fin,"%-20s%d\n",word[i].str,word[i].num);
system("pause");
}