[英]How do I count the number of words if the user enters multiple lines/spaces?
I have a char array, which contains what the user has inputted. 我有一个char数组,其中包含用户输入的内容。 How would I count the words?
我该如何计算单词? The user in permitted to to do something crazy like:
用户被允许做一些疯狂的事情,例如:
hello this
is a test
how are
you today?
So the number of words here should be 9 but my program tells me 23. Why is this not working? 所以这里的单词数应该是9,但是我的程序告诉我23.为什么不起作用? Its counting the spaces, but I have taken that into account with
sentence_entered[i + 1] != ' '
它计算空格,但是我已经考虑到了
sentence_entered[i + 1] != ' '
My code: 我的代码:
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++
}
The negation of a || b
a || b
的取反 a || b
is !a && !b
. a || b
是!a && !b
。
Your condition should read: 您的情况应为:
(sentence_entered[i] == ' ' ||
sentence_entered[i] == '\n') &&
(sentence_entered[i + 1] != ' ' &&
sentence_entered[i + 1] != '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.