c - 如何在不使用字符串的情况下计算单词总数?

标签 c word-count

我实现了这个代码来获得否。字数。它适用于所有单个字符,即如果我输入 "q w r " 作为输入,它会给我 3 个单词,但是当我输入 "qwe ed df " 作为输入时, 它显示 2.

#include<stdio.h>
int main()
{
    int c=getchar();

    int words=0;

    while(c!=EOF)
    {
        if(c==' ' || c=='\n')
        {
            c=getchar();
        }
        else if(c>='a' && c<='z')
        {  
            c=getchar();

            if(c==' ')
            {
                words=words+1;
                c=getchar();
            }
            else
            {
               c=getchar();
            }
        }
    }
    printf("%i\n",words);
}

最佳答案

诀窍是计算边界。

您的原始代码存在错误......

        if(c==' ')
        {
            words=words+1;
            c=getchar();
        }

只有当一对读取结果为 'a' => 'z' 后跟 ' ' 时,代码才计算单词数。

诀窍是将循环简化为一次读取一个字符的循环。 (这确保不会出现奇怪的边界),以及一个模拟您是在吃单词还是空格的状态机。

enum Mode { word = 1, spaces = 2 };
int c=getchar();
enum Mode currentMode = spaces;
int words=0;

while(c!=EOF)
{
    if(c==' ' || c=='\n')
    {
        if( currentMode == word ) {
            words=words+1;
        }
        currentMode = spaces;
    }
    else if(c>='a' && c<='z')
    {  
        currentMode = word;
    }
c=getchar();
}
// count the last word...
if( currentMode == word ) {
    words=words+1;
}

代码现在会忽略任何非字母字符,既不是单词也不是空格。

编辑:修复了不正确的枚举用法

关于c - 如何在不使用字符串的情况下计算单词总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38949764/

相关文章:

c - 将字典加载到 trie 树中的段错误

c 内存分配和数组的数组

c - 对于文件中每个可能的两个唯一单词对,打印出该对出现的次数

algorithm - 排序的 Trie 数据结构

python - 如何在python中获取word文档的字数?

c++ - Linux 内存分析工具

c - 在 free() 之后将指针设置为 NULL 总是一个好习惯吗?

c++ - 使用正则表达式的高效字数统计方法

hadoop - 我的 MapReduce 工作失败了

c - 如何通过 Eclipse 使用 C 写入 txt 文件(通过控制台输入)