当一个空字符串被传递给 find 函数时,它返回 0。
如果传递了未初始化的字符串,那么它也返回 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;
}
输出:
Loc:0
找到
我的问题是为什么 find 返回 0 而不是返回 string::npos ?