我试图在字符串中找到一个字符,但我得到了意想不到的结果.我的理解是,找不到它时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
Run Code Online (Sandbox Code Playgroud)
但是,在使用时==,代码按预期工作.
std::string s = "123456799";
if(s.find('8')==-1)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
//Output: Not Found
Run Code Online (Sandbox Code Playgroud)
我的理解是,找不到它时
string::find(char c)返回-1.
这不准确.根据文件:
返回值
如果找不到这样的子字符串,则找到的子字符串或npos的第一个字符的位置.
所以准确地说,未找到时std::string::find将返回std :: string :: npos.的一点是,该类型std::string::npos是std::string::size_type,这是一个无符号的整数类型.即使它是从价值初始化的-1,也不是-1; 它还没有签名.所以s.find('8')<0永远是false因为不可能是消极的.
Run Code Online (Sandbox Code Playgroud)static const size_type npos = -1;这是一个特殊值,等于类型可表示的最大值
size_type.
所以你应该使用std :: string :: npos来检查结果,以避免这种混淆.
if (s.find('8') == std::string::npos)
cout << "Not Found" << endl;
else
cout << "Found" << endl;
Run Code Online (Sandbox Code Playgroud)
if(s.find('8')==-1)工作正常,因为operator ==这里的左手操作数是无符号的,右边的操作数是有符号的.根据算术运算符的规则,
- 否则,如果无符号操作数的转换等级大于或等于带符号操作数的转换等级,则带符号操作数将转换为无符号操作数的类型.
因此-1将转换为unsigned,这是值,std::string::npos然后全部按预期工作.
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |