#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,正如我所料。为什么?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,正如我所料。为什么?std :: string.find_first_not_of,意外的返回值
您的通话比赛:
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
n
是字符的小号数量,以及你传递1.所以,你要搜索的第一个字符不是空间。您的" \t\n\v\f\r"
字符串的其余部分将被忽略。
有可能你只是想:
find_first_not_of(" \t\n\v\f\r")
第三个参数并不意味着你认为它。
根据this,string::find_first_not_of
搜索对象中不属于str,s或c的第一个字符,并返回其位置。由于“\ t”是这样的字符,所以返回值为0.
根据你想要打印的内容,我可以说第三个参数应该是你传递的字符串的长度。因此,这里是修正版本:
#include <stdio.h>
#include <string>
int main(void)
{
std::string s=" \t\n\v\f\r";
printf("%u\n", std::string("\n").find_first_not_of(s.c_str(), 0, s.length()));
//since now I'm using std::string, you can simply write:
printf("%u\n", std::string("\n").find_first_not_of(s));
}
演示在ideone:http://ideone.com/y5qCX
看到它:
#include <stdio.h>
#include <string>
int main(void)
{
std::string s("\n");
if(s.find_first_not_of(" \t\n\v\f\r", 0, 1) != std::string::npos)
printf("%u\n", s.find_first_not_of(" \t\n\v\f\r", 0, 1));
else
puts("npos");
return 0;
}
的方法find_first_not_of
解释最后一个参数为char的数量在其第一考虑参数,而不是在字符串中。
size_type std::string::find_first_not_of(
const char* str, size_type index, size_type num) const;
的论点num
是str
考虑,而不是在this
数!所以在你的情况下,它只考虑" \t\n\v\f\r"
的第一个字符。你的代码就相当于:
#include <cstdio>
#include <string>
int main(void)
{
printf("%u\n", std::string("\n").find_first_not_of(" ", 0));
}
如果你只想匹配std::string
的子,我想你必须明确的子叫find_first_not_of
,那就是:
#include <cstdio>
#include <string>
int main(void)
{
printf("%u\n", std::string("\n").substr(0, 1).find_first_not_of(" \t\n\v\f\r"));
}
BTW,here是该find_first_not_of
方法的行为的描述:
的find_first_not_of()函数之一:
- 返回当前字符串中的第一个字符不str中的任何字符匹配的索引,从index处开始搜索,字符串::非营利组织如果没有被发现,
- 搜索当前字符串开始处索引,对于与str中的第一个num字符不匹配的任何字符,返回符合此条件的第一个字符的当前字符串中的索引,否则返回string :: npos,
- 或返回第一个字符的索引在当前字符串中出现与ch不匹配的字符,如果没有找到任何内容,则在index处开始搜索,string :: npos。
'#包括
哦,是的,我知道,我只是从OP复制代码,并更新它来解释什么是不正确的。我没有试图纠正每个编码风格错误。我会改变它。 – 2011-03-12 19:43:45
不可思议! – 2011-03-12 19:08:19
@James:你也击败了我的西班牙人,这意味着你必须学习... – 2011-03-12 19:14:29