使用VC6.0編譯通過的
程式採用的是自頂而下的過程式編程,用動態數組來儲存單詞。對於字串的讀取則是採用一個一個的從檔案中讀取出來,並且同時對他們進行判斷,看是否是字母、‘-’、‘'‘;如果是則儲存在字串中,如果遇到不是,則加入字串結束符並且對整個字串進行處理。對於字串的尋找和插入,則採用的是二分尋找和順序插入的演算法;最後利用選擇排序,選出最多的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");
}
http://tanyufeng521.weebly.com/1/post/2012/03/4.html