C - 如何计算文本文件中的单词?

时间:2014-01-25 23:19:48

标签: c

所以我应该计算一个包含多行的txt文件中有多少单词,并将单词定义为连续的字母序列(a到z,A到Z)和撇号由任何字符分隔超出这些范围。

我的想法看起来很正确,但是wordcount一直出错。有没有人看到我的代码有什么奇怪的东西?

请忽略linecount和charcount,因为它们正常工作。我尝试计算单词之间的空格,其中32是空格的ASCII代码。

#include <stdio.h>

int main()
{
int c;
int charcount = 0;
int wordcount = 1;
int linecount = 0;

while (c != EOF)
{
    c = getchar();
    if (c == EOF)
        break;
    if (c == 10)
        linecount++;

    charcount++;

    if (c == 32)
        wordcount++;

}

printf ("%d %d %d\n", charcount, wordcount, linecount);
return 0;

}

例如,其中一个txt文件说:

Said Hamlet to Ophelia,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?

这里的字数是21,但我得到了18的字数。我尝试计算“/ n”的数量,它适用于这个测试,但是它无法用于下一个测试。

提前致谢!

2 个答案:

答案 0 :(得分:1)

包含ctype.h然后更改

if (c == 32)
    wordcount++

if (isspace(c))
    wordcount++

单词由空格,制表符和行字符分隔。

答案 1 :(得分:-1)

使用以C:

编码的简单FSM
#include <stdio.h>
#include <ctype.h>

enum {INITIAL,WORD,SPACE};

int main()
{
  int c;
  int state = INITIAL;
  int wcount = 0;

  c = getchar();
  while (c != EOF)
  {
    switch (state)
    {
      case INITIAL: wcount = 0;
                    if (isalpha(c) || c=='\'')
                    {
                       wcount++;
                       state = WORD;
                    }
                    else
                       state = SPACE;
                    break;

      case WORD:    if (!isalpha(c) && c!='\'')
                       state = SPACE;
                    break;

      case SPACE:   if (isalpha(c) || c=='\'')
                    {
                       wcount++;
                       state = WORD;
                    }
    }
    c = getchar();
  }
  printf ("%d words\n", wcount);
  return 0;
}