統計檔案中單詞的個數
include”stdafx.h”
include
include
include
define Inti_word 0
define In_word 1
define Out_word 2
define End_word 3
int Count_word(char *str)
{
int n = 0;
if(NULL == str)
{
return n;
}
int tag = Inti_word;
for(int i=0; str[i]!=’\0’; i++)
{
switch(tag)
{
case Inti_word:
if(isalpha(str[i]))
{
tag = In_word;
}
else
{
tag = Out_word;
break;
}
case In_word:
if(!isalpha(str[i]))
{
if((str[i]!=39) && (str[i]!=’-‘)) //str[i]!=/’
{
tag = Out_word;
n += 1;
}
}
break;
case Out_word:
if(isalpha(str[i]))
{
tag = In_word;
}
break;
case End_word:
break;
}
}
if(tag == In_word)
n += 1;
return n;
}
int main()
{
char ch[100]; //為何字串長度小於97不能執行?
int num = 0;
int i = 0;
FILE *fp = fopen(“jiadai.txt”,”r”);
if(fp == NULL)
{
printf(“file open error!\n”);
exit(0);
}
while(!feof(fp))
{
fgets(ch, sizeof(char)*100, fp);
printf(“%s”, ch);
num += Count_word(ch);
}
printf(“\n%d”, num);
printf(“\n”);
fclose(fp);
fp = NULL;
return 0;
}