[英]How to count words in a document assuming the text file has multiple spaces
目标基本上是重新创建wc
。 我需要计算单词,字符,非空白字符和换行符。 除了语言我什么都弄不清,我不知道该怎么做。
当我在这里搜索时,每个人都以为文档中单词之间没有多个空格。 我必须测试的文档保证有多个空格,因此这种计算单词的方法不起作用。
#include <stdio.h>
int main (int argc, char* argv[]) {
int Spaces;
Spaces = 0;
int NewLine;
NewLine = 0;
int Characters;
Characters = -1;
char* filename = argv[1];
if (argc < 2) {
printf("Usage: \n wc <filename>\n");
} else {
printf("Filename is: %s\n", filename );
FILE* infile;
infile = fopen(filename, "r");
char c;
do {
if (c == ' ') {
Spaces = Spaces + 1;
}
if (c == '\n') {
NewLine = NewLine + 1;
}
Characters = Characters + 1;
} while ((c = fgetc(infile)) != EOF);
printf("Total number of characters: %d\n", Characters);
Characters = Characters - NewLine - Spaces;
printf("Total number of non-whitespace characters: %d\n", Characters);
printf("Total number of lines: %d\n", NewLine);
}
return 0;
}
通常情况下,你使用一个布尔变量,通常命名为类似in_word
,你设置为false
,如果当前字符是空白,而true
,如果它不是。 当单词计数从( true
变为false
(反之亦然)时,才增加单词计数。
将您的代码实现为具有两种状态:一个字和一个字。 然后在状态之间转换时增加计数。
我建议在从单字转换到单字转换时增加字数(与从单字转换为单字转换相反),因此最后不需要进行特殊处理文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.