我正在尝试在字符串中查找一个字符,但结果出乎意料。据我所知,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
然而,当使用
==
时,代码按预期工作。std::string s = "123456799";
if(s.find('8')==-1)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Not Found
npos
的类型是无符号的;它被初始化为-1
并不意味着它是负数。请注意这里的解释(http://en.cppreference.com/w/cpp/string/basic_string/npos),“这是一个特殊值,等于类型 size_type 可表示的最大值。” - songyuanyaonpos
,请返回npos
。 - PaulMcKenzie