C ++: Is the behavior of the string :: find for an empty input string correct

The following code fragment always returns true in my compiler (visual studio). But is this behavior well tolerated?

bool return_always_true(std::string const& str)
{
    return str.find("") != std::string::npos;
}

int main(){
     cout << boolapha << return_always_true("") << endl
          << return_always_true("oxylottl") << endl
          << return_always_true("lorem ipsum") << endl;
 //true true true
}
+4
source share
3 answers

I find cppreference.com more readable than the standard. Quoting them:

Finds the first substring equal to str...

Formally, a substring stris called found in position xposif all of the following is true:

  • xpos >= pos
  • xpos + str.size() <= size()
  • for all positions nin str,Traits::eq(at(xpos+n), str.at(n))

An empty line will always match at the beginning of the target line, because

  • 0> = 0
  • 0 + 0 <= size ()
  • str, .
+8

, : " pos , pos <= size()"

+3

According to cppreference :

  • an empty substring is found in pos if and only if pos <= size ()

str.find("")uses the third overload for std::basic_string::find, which has a signature:

size_type find( const CharT* s, size_type pos = 0 ) const;

This means that it posstarts with 0, therefore it is pos <= size()always true.

Yes, the behavior is well defined and tolerable.

+3
source

Source: https://habr.com/ru/post/1658002/


All Articles