Reputation: 19
When a empty string is passed to find function it returns 0.
If uninitialized string is passed, then also it returns 0.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1="";
string str2="This is a sample string";
unsigned int loc = str2.find(str1);
cout << "Loc : " << loc << endl;
if(loc != string::npos)
{
cout << "Found" << endl;
}
else
{
cout << "Not found" << endl;
}
return 0;
}
Output :
Loc : 0
Found
My question is why does find return 0 instead of returning string::npos ?
Upvotes: 1
Views: 1245
Reputation: 22334
It found the exact match at position 0 (the first one searched), so that index is returned.
Quoting from cppreference, the conditions are:
Formally, a substring
str
is said to be found at positionxpos
if all of the following is true:
xpos >= pos
xpos + str.size() <= size()
- for all positions
n
instr
,Traits::eq(at(xpos+n), str.at(n))
Trying to match substring from position 0, we get that
Upvotes: 1
Reputation: 16761
As the docs on cppreference say. (Emphasis is mine.)
Finds the first substring equal to the given character sequence. Search begins at pos, i.e. the found substring must not begin in a position preceding pos.
- Finds the first substring equal to
str
.
When is a string found at a position?
Formally, a substring str is said to be found at position xpos if all of the following is true:
xpos >= pos
xpos + str.size() <= size()
- for all positions
n
instr
,Traits::eq(at(xpos+n), str.at(n))
An empty string fulfills these requirements at position 0.
The docs further say. (Emphasis is mine.)
In particular, this implies that
- a substring can be found only if
pos <= size() - str.size()
- an empty substring is found at
pos
if and only ifpos <= size()
- for a non-empty substring, if
pos >= size()
, the function always returnsnpos
.
Upvotes: 2
Reputation: 117771
A needle l
can be found in position i
of haystack h
if i + len(l) <= len(h)
and for all 0 <= k < len(l)
we have l[k] == h[i+k]
. What you're dealing with is simply the vacuous truth of this definition: 'for all x' automatically becomes true if there's no valid x to begin with.
Upvotes: 5