1.2 单词统计
【问题】
统计某篇英文小说中某单词的出现次数,并输出单词所在的句子。
【提示】
英文小说存储在一个文本文件中。一个单词是由空格或标点符号(含换行符)分隔的字符序列,且约定小说中的词汇一律不跨行;句号(.)或分号(;)唯一确定一个句子。文本文件名和待统计的单词由键盘输入,输出单词所在的句子和出现次数。
可设计两个函数:getsentence(str1,fp)从fp文件读取一句存放在字符数组str1中;checkword(str1,str2)检查存放在字符数组str2中的单词是否出现在str1中的句子中,若出现则输出该句子并返回单词在句子中的出现次数。
以下是我写的源程序,没有完全按照提示来:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define N 200
#define M 20
static int sum=0;/*sum是用来记录目标单词总共出现的次数,必须用static型*/
void checkword(char* p1,char* objectword){     
     char temp[M];/*这个数组是用来存取从句子中提取出来的单词*/
     int i=0,j,count=0;
     while(p1[i]!='\0'){
        j=0; 
        while(isalpha(p1[i])){/*用来检测p1[i]是不是字母*/
           temp[j]=p1[i];
           i++;
           j++;
        }
        temp[j]='\0';
        if(strcmp(temp,objectword)==0)/*判断提取出来的单词是否与要查找的单词一致*/
           count++;
        while(!isalpha(p1[i])&&p1[i]!='\0'){
           i++; 
        } 
     }
     if(count!=0){
        printf("%s\n",p1);
        sum+=count; 
     }          
}
void getsentence(char* p1,FILE* p2,char* objectword){
     int i;
     char ch;
     ch=fgetc(p2);
     while(ch!=EOF){
        i=0;
        while(ch!='.'&&ch!=';'&&ch!=EOF){
            p1[i]=ch;
            i++;
            ch=fgetc(p2);
 
        }
        if(ch=='.'||ch==';'){
           p1[i]=ch;
           p1[i+1]='\0';    
           checkword(p1,objectword);
           ch=fgetc(p2);
        }
     }
}
int main(){
    char str1[N],str2[M],filename[M];
    char ch;
    FILE* fp;
    printf("Please input the name of the file:\n");
    scanf("%s",filename);
    printf("Please input the word which you want to search:\n");
    scanf("%s",str2);
    fp=fopen(filename,"r");
    if(fp==NULL){
       printf("cannot open the file\n");
       exit(0);
    }
    getsentence(str1,fp,str2);
    printf("The word which you want to search in the file has been appeared %d times in total!\n",sum);
    fclose(fp);
    system("pause");
    return 0;
}
程序在devcpp下调试通过,基本没什么问题,望高手们能够给出更好的代码!

 
											





 
	    

