且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当使用== - 1时,string.find()返回true,当使用< 0时返回false

更新时间:2023-02-26 20:26:02


我的理解是, string :: find(char c)返回 -1 当它没有被发现。


这是不准确的。根据文档


返回值

如果找不到
这样的子字符串,找到的子字符串或npos的第一个字符的位置。


所以准确的说,当找不到 std :: string :: find 时,会返回 std :: string :: npos 。重点是 std :: string :: npos 的类型是 std :: string :: size_type ,是一个无符号整数类型。即使它是从 -1 的值初始化的,它不是 -1 ;它仍然没有签名。所以 s.find('8')将始终为 false ,因为不可能是负数。



std :: string :: npos


  static const size_type npos = -1; 

这是一个特殊值,等于 size_type


所以你应该使用 std :: string :: npos 检查结果,避免这种混淆。


$ b如果(s.find('8')== std :: string :: npos)
cout<< 未找到<< ENDL;
else
cout<< 找到<< ENDL;






if(s。 find('8')== - 1)可以正常工作,因为 operator == 这里是没有签名的,右边的是签名的。根据算术运算符的规则,

$ b否则,如果无符号操作数的转换等级大于或等于有符号操作数的转换等级,则将有符号操作数转换为

所以 -1 将被转换为无符号,这是 std :: string :: npos 的值,然后按预期工作。

I am trying to find a character within a string but I am getting unexpected results. My understanding is that string::find(char c) returns -1 when it is not found. However, I am getting some unexpected results.

Even though the string does not include an '8', it is still returning true.

std::string s = "123456799";
if(s.find('8')<0)
    cout << "Not Found" << endl;
else
    cout <<  "Found" << endl;

//Output: Found

However, when using == instead the code works as expected.

std::string s = "123456799";
if(s.find('8')==-1)
    cout << "Not Found" << endl;
else
    cout <<  "Found" << endl;

//Output: Not Found

My understanding is that string::find(char c) returns -1 when it is not found.

It's not accurate. According to the documentation:

Return value
Position of the first character of the found substring or npos if no such substring is found.

So to be precise, when not found std::string::find will return std::string::npos. The point is that the type of std::string::npos is std::string::size_type, which is an unsigned integer type. Even it's initialized from value of -1, it's not -1; it's still unsigned. So s.find('8')<0 will always be false because it's not possible to be negative.

Documentation of std::string::npos:

static const size_type npos = -1;

This is a special value equal to the maximum value representable by the type size_type.

So you should use std::string::npos for checking the result, to avoid such kind of confusing.

if (s.find('8') == std::string::npos)
    cout << "Not Found" << endl;
else
    cout <<  "Found" << endl;


if(s.find('8')==-1) works fine, because the left-hand operand of operator== here is unsigned, the right-hand one is signed. According to the rules for arithmetic operators,

  • Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

So -1 will be converted to unsigned, which is the value of std::string::npos and then all work as expected.