计算一个单词在一个文件中的次数 [英] Counting how many times a word is in a file

查看:84
本文介绍了计算一个单词在一个文件中的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个获取字符串的程序,并计算在特定文件中找到该字符串的次数.

I'm trying to write a program that gets a string, and counts how many times that string is found in a specific file.

文件当前为:你好,我的名字你好,是oria我喜欢编程

The file is currently: hello my name hello is oria I like hello to program

我要数的单词是你好.

这是我的代码

int num_of_words(FILE* stream,char* str)
{
    int count=0,i=0,length;
    char c;
    rewind(stream);
    length=strlen(str);
    do
    {
        c=fgetc(stream);
        while(c==*(str+i))
        {
            c=fgetc(stream);
            i++;
            if(i==length)
            {
                count++;
                i=0;
            }
        }
        i=0;
    }while(c!=EOF);
    return count;
}

这个想法是,存在一个称为i的特定索引,并且仅当字母之间存在匹配时才前进.如果我达到了字符串的长度,则意味着我们相继找到了所有字母,并且我将计数加1.

The idea is that there is a certain index called i, and it advances only if there is a match between letters. if i reached the length of the string, then it means we found all the letters in succession, and i raise count by one.

由于某种原因,它总是返回零.

For some reason, it always returns zero.

推荐答案

I. while(!eof)是错误的

I. while (!eof) is wrong.

II.不要重新发明轮子-有 strstr()标准C库中的函数,可帮助您在另一个字符串中找到子字符串.

II. Don't reinvent the wheel - there's the strstr() function in the C standard library which helps you find a substring in another string.

我宁愿将文件读入缓冲区,然后使用以下功能.如果文件不是太大,那应该没有问题.

I'd rather read the file into a buffer then use the following function. If the file is not too large, this should not be a problem.

int count(const char *haystack, const char *needle)
{
    int n = 0;
    const char *p = haystack;
    size_t len = strlen(needle);
    while (p = strstr(p, needle)) {
        n++;
        p += len;
    }

    return n;
}

这篇关于计算一个单词在一个文件中的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆