Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: Is the behavior of string::find for empty input string well defined

The following code snippet returns always true on my compiler(visual studio). But is this behavior well defined and portable?

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
}
like image 814
user1235183 Avatar asked Dec 07 '22 20:12

user1235183


2 Answers

I find cppreference.com easier to read than the standard. Quoting them:

Finds the first substring equal to str ...

Formally, a substring str is said to be found at position xpos if all of the following is true:

  1. xpos >= pos
  2. xpos + str.size() <= size()
  3. for all positions n in str, Traits::eq(at(xpos+n), str.at(n))

An empty string will always match at the start of the target string because

  1. 0 >= 0
  2. 0+0 <= size()
  3. There are no position is str so the match condition is vacuously true.
like image 140
Martin Bonner supports Monica Avatar answered Dec 28 '22 22:12

Martin Bonner supports Monica


Yes it is: "an empty substring is found at pos if and only if pos <= size()"

like image 31
Aaron Avatar answered Dec 29 '22 00:12

Aaron