c - 我如何计算段落中的单词数?我一直数错
问题描述
我正在尝试编写一个程序来计算文本中的字母、单词和句子的数量。我可以假设一个字母是从 a 到 z 的任何小写字符或从 A 到 Z 的任何大写字符,任何由空格分隔的字符序列都应该算作一个单词,并且任何出现的句点、感叹号或问号表示句子的结束。
到目前为止,我可以正确计算字母和句子的数量,但我错过了单词的数量:
例如,是的!
输出应该是: 3 个字母 1 个单词 1 个句子
我得到的是: 3 个字母 0 个单词 1 个句子
更新:在 printf 函数之前最后输入另一个(words++)后,它现在可以正常工作了。感谢您的帮助:)。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string text = get_string("Enter text: ");
printf("Output:\n");
int lettercount;
int words = 0;
int sentences = 0;
int letters = 0;
int length = strlen(text);
for(lettercount = 0; lettercount < length; lettercount++)
{
if(isalpha(text[lettercount]))
{
letters++;
}
else if(text[lettercount] == ' ' || text[lettercount] == '\t' || text[lettercount] == '\n' || text[lettercount] == '\0')
{
words++;
}
else if(text[lettercount] == '.' || text[lettercount] == '!' || text[lettercount] == '?')
{
sentences++;
}
}
words++;
printf("%i letter(s)\n", letters);
printf("%i word(s)\n", words);
printf("%i sentence(s)\n", sentences);
}
解决方案
您的代码的主要问题是,如果输入文本中没有空格,则它不会计算输入文本中的任何“最终”单词(终止'\0'
字符将不是测试字符串的一部分,因为该strlen
函数不包含该字符) .
此外,如果您的单词被多个空格分隔,您将遇到问题;为了解决这个问题,您可以使用一个inWord
标志来跟踪当前字符是否已经在一个单词中,如果没有,则在我们找到一个字母时设置该标志。
此外,如果您的输入中有类似的内容,您的句子计数将会有问题"..."
;您的行后面的注释掉的sentences++;
行将解决该问题(如果您愿意)。
最后,准确地说,你不应该假设字母“a”到“z”和“A”到“Z”将是连续的序列。它们可能会(现在大多数系统都使用 ASCII 编码),但您应该使用该isalpha
函数以获得更多可移植性(以及该isspace
函数)。
int main(void)
{
string text = get_string("Enter text: ");
printf("Output:\n");
int lettercount;
int words = 0;
int sentences = 0;
int letters = 0;
int inWord = 0;// Set to 1 if we are inside a (new) word!
int length = (int)(strlen(text)); // Don't evaluate length on each loop!
for (lettercount = 0; lettercount < length; lettercount++) {
int testChar = text[lettercount]; // Get a local copy of the current character
if (isalpha(testChar)) { // Don't assume that 'a' ... 'z' and 'A' ... 'Z' are in contiguous sequences
letters++;
if (!inWord) words++; // Any letter means that we're in a (possibly new) word...
inWord = 1; // ... but now set this 'flag' so as not to count others!
}
else if (testChar == '.' || testChar == '!' || testChar == '?') {
sentences++;
// if (inWord) sentences++; // Check that we're in a word, or stuff like "..." will be wrong
inWord = 0; // Now we are no longer inside our current word
}
else if (isspace(testChar)) { // We could also just assume ANY other character is a non-word
inWord = 0; // Now we are no longer inside our current word
}
}
printf("%i letter(s)\n", letters);
printf("%i word(s)\n", words);
printf("%i sentence(s)\n", sentences);
return 0;
}
随时要求任何进一步的澄清和/或解释。
推荐阅读
- python-3.x - sklearn 与 Linux-alpine 兼容吗?
- php - 如何在php中打印数组的名称
- debugging - 在 WinDbg 内存窗口中查看结构的语法?
- ios - 停止/暂停在 tableview 单元类中创建的 avplayer
- java - 在powermock的静态方法中模拟静态方法
- c# - MediaPlayer 并不总是在 UWP 应用中播放音频
- wordpress - Google Search Console - 验证失败
- postgresql - 如何嗅探 PostgreSQL 网络流量?
- jquery - 禁用/启用的 dom 元素的 JQuery 自动完成
- database - 字段为文本类型的 sqlite3 查询中的错误