[英]How do I count the number of words if the user enters multiple lines/spaces?
我有一个char数组,其中包含用户输入的内容。 我该如何计算单词? 用户被允许做一些疯狂的事情,例如:
hello this
is a test
how are
you today?
所以这里的单词数应该是9,但是我的程序告诉我23.为什么不起作用? 它计算空格,但是我已经考虑到了sentence_entered[i + 1] != ' '
我的代码:
int i = 0;
while (sentence_entered[i] != '\0') {
if (
(sentence_entered[i] == ' ' ||
sentence_entered[i] == '\n') &&
(sentence_entered[i + 1] != ' ' ||
sentence_entered[i + 1] != '\n')
) {
words += 1;
}
i++
}
a || b
的取反 a || b
是!a && !b
。
您的情况应为:
(sentence_entered[i] == ' ' ||
sentence_entered[i] == '\n') &&
(sentence_entered[i + 1] != ' ' &&
sentence_entered[i + 1] != '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.