C++ string.find()在使用==-1时返回true,而在使用<;时返回false;使用0
我试图在字符串中找到一个字符,但得到了意外的结果。我的理解是C++ string.find()在使用==-1时返回true,而在使用<;时返回false;使用0,c++,string,find,C++,String,Find,我试图在字符串中找到一个字符,但得到了意外的结果。我的理解是string::find(char c)在未找到时返回-1。然而,我得到了一些意想不到的结果 即使字符串不包含'8',它仍然返回true std::string s = "123456799"; if(s.find('8')<0) cout << "Not Found" << endl; else cout << "Found" << endl; //Output
string::find(char c)
在未找到时返回-1
。然而,我得到了一些意想不到的结果
即使字符串不包含'8'
,它仍然返回true
std::string s = "123456799";
if(s.find('8')<0)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Found
string::find()
返回size\t
,它是一个无符号整数,因此永远不能为负
我的理解是string::find(char c)
在未找到时返回-1
这不准确。根据报告:
返回值找到的子字符串或NPO的第一个字符的位置(如果没有) 发现了这样的子串
所以准确地说,当未找到时,
std::string::find
将返回。关键是std::string::npos
的类型是std::string::size\u type
,这是一种无符号整数类型。即使它是从-1
的值初始化的,它也不是-1
;它仍然没有签名。所以s.find('8')。它在哪里说std::string\u find
返回-1
?@PaulMcKenzie std::string\u find返回string::npos如果没有找到,string::npos是“static const size\u t npos=-1;”@用户3196144注意npo
的类型是无符号的;它用值-1初始化,但这并不意味着它是负数。注意解释,“这是一个特殊值,等于type size_type表示的最大值。”@user3196144并注意到OP遵循了您的建议,现在不得不问一个问题,以解释为什么他们的程序无法工作。请务必阅读文档。如果函数返回一个值,并且该值被命名为npos
,则返回npos
。
std::string s = "123456799";
if(s.find('8')==-1)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Not Found
static const size_type npos = -1;
if (s.find('8') == std::string::npos)
cout << "Not Found" << endl;
else
cout << "Found" << endl;