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 ?
string str1;str1is initialized; the default constructor is used to initialize the string which happens to initialize it as the empty string. It's rather hard to get an uninitialized string. you'll need to jump some hoops to get an uninitialized string:void* memory = std::malloc(sizeof(std::string)); std::string* uninitializedStringPointer = static_cast<std::string*>(memory);