简体   繁体   中英

std::string::find not working as expected in c++

I am trying to verify if a specific string is in the input string and if so do something, based on the found string; but it seems that it is always doing the first task no matter what...

if (inputString.find(str1) >= 0)
{
   //do something
}
else if (inputString.find(str2) >= 0)
{
    // do something else
}
else 
{
    std::cout << "Strange" << std::endl;
}

It is always entering the // do something block no matter if the str1 is present in inputString or not.

If I do

int str1pos = inputString.find(str1);
int str2pos = inputString.find(str2);
if (str1pos >= 0)
{
   //do something
}
else if (str2pos >= 0)
{
    // do something else
}
else 
{
    std::cout << "Strange" << std::endl;
}

it seems to work. Why is that? What am I doing wrong?

inputString.find(str1) >= 0 is always true.

This is because the return type of find is size_t which is an unsigned integer type, so it cannot be negative. Any decent compiler will give a warning for this comparison.

In your second example, when you convert the return value of find to int , if find returned npos , then the value becomes -1 . That's why >= 0 works there. But if find returned a value greater than INT_MAX but not npos , the cast would turn the index to a negative value, and your logic would fail.

Therefore, you should compare to npos instead:

if (inputString.find(str1) != std::string::npos)

std::string::find returns std::string::npos if the input string is not found. To check if the string contains your input string, you must use:

if (inputString.find(str1) != std::string::npos)
{
   //do something
}
else if (inputString.find(str2) != std::string::npos)
{
    // do something else
}
else 
{
    std::cout << "Strange" << std::endl;
}

When not found, the return value is std::string::npos . It could be a positive number. You don't know.

Change your code into

if (inputString.find(str1) != std::string::npos)
{
   //do something
}
else if (inputString.find(str2) != std::string::npos)
{
    // do something else
}
else 
{
    std::cout << "Strange" << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM