我不能数多个角色
我正在尝试构建一个函数,该函数计算文本中有多少个句子,具体取决于?
,!
和。
来决定句子的结尾。
出于某种原因,无论有多少函数的功能都不会计算超过一个,并且只有在整个文本的末尾。
这是功能:
int count_sentences(string text) {
int count = 0;
for (int i = 0; i < strlen(text); i++) {
if (strcmp(&text[i], "?") == 0 || strcmp(&text[i], "!") == 0
|| strcmp(&text[i], ".") == 0) {
count += 1;
}
}
return count;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
strcmp
用于比较零终止字符串。您只想比较字符。让我们假设
文本
包含”。ABC“
。在第一次迭代期间(当
i
US 0时),&amp; text [i]
指向字符串“。ABC”
andstrcmp(&amp; text [i],“。”)
实际上将字符串“。abc”
与字符串“。”。当然,不相等。您的if语句应该这样:
strcmp
is for comparing null terminated strings. You just want to compare characters.Let's assume
text
contains".ABC"
.During the first iteration (when
i
us 0),&text[i]
points to the string".ABC"
andstrcmp(&text[i], ".")
actually compares the string".ABC"
to the string"."
and they are, of course, not equal.Your if statement should be like this:
使用函数
strcmp
没有意义。如果字符串
text
中的最后一个字符将在if语句中的表达式进行评估,前提是最后一个字符等于字符'?'?'
,'!'
和'。'
。相反,您应该使用标准C函数
strspn
和strcspn
。例如,该函数将返回1字符串
“执行...”
。确实,尽管有三个字符'。'
,只有一个语句。这是一个演示程序。
程序输出是
Using the function
strcmp
does not make a sense. The expression in the if statement will be evaluated to true only for the last character in the string
text
provided that the last character is equal to one of the characters'?'
,'!'
and'.'
.Instead you should use standard C functions
strspn
andstrcspn
. For exampleThe function will return 1 for example for the string
"Executing..."
. Indeed there is only one statement though there are three characters'.'
.Here is a demonstration program.
The program output is
您的代码不起作用,因为
&amp; text [i]
不是1个字符字符串,而是text
从Offset开始的字符串部分的指针我
。当您观察到时,只有最后一个字符才能正确测试。您应该以这种方式而不是字符串,而是应该这样的单个字符:
但是,请注意,对于不以句子分离器结束的字符串,此代码不会正常工作,如果多个分隔符在一起:
“ Hello”
> ,“ Hello!”
,“对不起...”
。计算此类句子的诀窍是列举从分离器到非分离器的过渡。此方法可以计算单词,行等。
这是一个修改版本:
Your code does not work because
&text[i]
is not a 1 character string, but a pointer to the part of the string intext
starting at offseti
. Only the last character will be tested correctly as you observe.Instead of strings, you should instead individual characters this way:
Note however that this code will not work as expected for strings that do not end with a sentence separator, neither if multiple separators occur together:
"hello"
,"Hello!!!"
,"Sorry..."
.The trick to count such sentences is to enumerate transitions from separators to non separators. This method works to count words, lines etc.
Here is a modified version:
您传递的指针使您比较以下字符。使用
字符串[index] =='?'
比较单个字符。The pointer you passed in causes you to compare the following characters. Use
string[index] == '?'
to compare individual characters.https://code.woboq.org/userspace/glibc/string/strcmp.c.html