文本文件单词的检索及计数

要求编程建立一个文本文件,每个单词不包括空格及跨行,单词由字符序列构成且区分大小写,完成以下功能:统计给定单词在文本文件中出现的总次数、检索输出某单词在文本文件中首次出现的行号及位置。
代码如下

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void creatfile(FILE* fp)
{
    char ch[1024];
    //输入文本内容,以#结束
    printf("\nEnter the contents of this file. End with # in the beginning of a line:\n");
    fgets(ch,1024,stdin);
    while(ch[0]!='#')
    {
        //写入文件
        fputs(ch,fp);
  fgets(ch,1024,stdin);
    }
}
void search(FILE* fp,char b[])
{
    //a[50]存放当前单词
    char ch,a[50];
    //定义单词第一次出现的行和列
    int first_row,first_col;
    int index=0,row=1,col=0,count=0;   //count为该单词出现的次数,col为该单词是此行的第几个,row为单词出现的行号
    //文件指针没有达到末尾时
    while(!feof(fp))
    {
       ch=fgetc(fp);
       if(isalpha(ch))
        {
            a[index]=ch;
            index++;
        }
        else if(ch==' ')
        {
          if(index!=0)
            {
                col++;
            }
            a[index]='\0';//表示字符串结束
            index=0;
            if(strcmp(a,b)==0)
            {
                count++;
                if(count==1)
                {
                    first_row=row;
                    first_col=col;
                }
            }
            }
        //当前字符为回车时
        else if(ch=='\n')
        {
            a[index]='\0';
            row++;
            index=0;
            col=0;
            if(strcmp(a,b)==0)
            {
               count++;
                if(count==1)
                {
                    first_row=row;
                    first_col=col;
                }
            }
            }}
            printf("This word appears %d time(s) in total.\n",count);
            if(cout>0)
            {
                 printf("The word %s first appears in line:%d,column:%d",b,first_row,first_col);
                }
       }
  int main()
  {
    char b[50];
    FILE *fp;
    fp=fopen("word_search.txt","w+");
    creatfile(fp);
    printf("\nEnter the word you want to search:\n");
    scanf("%s",b);
    rewind(fp);
    search(fp,b);
    //操作完毕,关闭文件
    fclose(fp);
    return 0;
    }
         



总结一下我在写的时候以及交作业的时候遇到的问题:
1.在createfile()执行以后要使用rewind()函数,使文件指针重新回到文件起始位置。
2.在检测到当前字符为空格或回车时要令a[index]=’\0’,表示字符串的结束;

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值