如果作为参数传递的字符串为空,则C++中的字符串查找函数返回0
当一个空字符串被传递给 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;
}
输出:位置
:0
找到
我的问题是为什么 find 返回 0 而不是返回 string::npos ?
回答
一针l的位置是可以找到i草垛h,如果i + len(l) <= len(h)为所有0 <= k < len(l)我们有l[k] == h[i+k]。您正在处理的只是这个定义的空洞真理:如果没有有效的x开始,“对于所有x ”自动变为真。