[英]C - How to count words in a txt file?
因此,我应该计算一个多行文本文件中有多少个单词,单词被定义为连续的字母序列(a到z,A到Z),并且撇号被这些范围之外的任何字符分隔。
我有我认为正确的内容,但字数不断出现错误。 有人看到我的代码有些奇怪吗?
请忽略行数和字符数,因为它们工作正常。 我尝试计算单词之间的空格,其中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”的数量,它在此测试中有效,但在下一个测试中失败。
提前致谢!
包含ctype.h然后更改
if (c == 32)
wordcount++
至
if (isspace(c))
wordcount++
单词由空格,制表符和行字符分隔。
使用用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.