2011-03-12 94 views

回答

5

您的通话比赛:

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") 
2

第三个参数并不意味着你认为它。

+3

不可思议! – 2011-03-12 19:08:19

+0

@James:你也击败了我的西班牙人,这意味着你必须学习... – 2011-03-12 19:14:29

0

根据this,string::find_first_not_of搜索对象中不属于str,s或c的第一个字符,并返回其位置。由于“\ t”是这样的字符,所以返回值为0.

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

+0

@詹姆斯:但我通过'char *' – Nawaz 2011-03-12 19:08:13

+0

'char *'以null结尾; 'find_first_not_of'可以在不显式传递's.length()'的情况下确定字符的数量。 – 2011-03-12 19:10:38

+0

@詹姆斯:是的。你是对的,但我正在展示第三个论点的意义! – Nawaz 2011-03-12 19:11:37

0

看到它:

#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; 
} 
0

的方法find_first_not_of解释最后一个参数为char的数量在其第一考虑参数,而不是在字符串中。

size_type std::string::find_first_not_of(
    const char* str, size_type index, size_type num) const; 

的论点numstr考虑,而不是在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。
+0

'#包括'是一个坏习惯。使用'#include ' – Erik 2011-03-12 19:21:49

+0

哦,是的,我知道,我只是从OP复制代码,并更新它来解释什么是不正确的。我没有试图纠正每个编码风格错误。我会改变它。 – 2011-03-12 19:43:45