Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c++ - string.find() returns true when ==-1 is used but false when <0 is used

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...