std::string.find_first_not_of,意外的返回值
#include <stdio.h>
#include <string>
int main(void)
{
printf("%u\n", std::string("\n").find_first_not_of(" \t\n\v\f\r", 0, 1));
}
下面的程序打印 0,而不是我预期的 std::string::npos 。为什么?
#include <stdio.h>
#include <string>
int main(void)
{
printf("%u\n", std::string("\n").find_first_not_of(" \t\n\v\f\r", 0, 1));
}
The following program prints 0, not std::string::npos as I expected. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的调用匹配:
n
是 s 中的字符数,并且您传递的是 1。因此,您正在搜索第一个不是空格的字符。其余的" \t\n\v\f\r"
字符串将被忽略。可能您只是想要:
Your call matches:
n
is the number of chars in s, and you're passing 1. So, you're searching for the first char that is not space. The rest of your" \t\n\v\f\r"
string is ignored.Likely you simply want:
第三个参数并不意味着你认为它的作用。
The third parameter doesn't mean what you think it does.
根据this,
string::find_first_not_of
搜索对象中不属于 str、s 或 c 的第一个字符,并返回其位置。由于“\t”是此类字符,因此返回值为0。According to this,
string::find_first_not_of
searches for the first character in the object which is not part of either str, s or c, and returns its position. Since "\t" is such character, return value is 0.根据您想要打印的内容,我可以说第三个参数应该是您传递的字符串的长度。所以这里是更正后的版本:
ideone 的演示: http://ideone.com/y5qCX
Based on what you want to print, I can say the third parameter should be the length of string you passed. So here is the corrected version:
Demo at ideone : http://ideone.com/y5qCX
看看它:
See it:
find_first_not_of 方法将最后一个参数解释为第一个参数中要考虑的字符数,而不是字符串中的字符数。
参数
num
是在str
中考虑的数字,而不是在this
中!因此,在您的情况下,它只考虑" \t\n\v\f\r"
的第一个字符。您的代码相当于:如果您只想匹配
std::string
的子字符串,我认为您必须在显式子字符串上调用find_first_not_of
,即:BTW ,这里是
find_first_not_of 方法:
The method
find_first_not_of
interpret the last argument as the number of char to consider in its first argument, not in the string.The argument
num
is the number to consider instr
, not inthis
! So in your case, it only consider the first caracter of" \t\n\v\f\r"
. You code is equivalent to:If you want to only match a substring of the
std::string
, I think you must callfind_first_not_of
on an explicit substring, that is:BTW, here is the description of the behavior of the
find_first_not_of
method: