关于stl string find 容易犯的一个错误

时间:2023-03-10 05:39:42
关于stl string find 容易犯的一个错误

有时候经常会判断一个字符串a中是否有子字符串b,那么有人会调用 string::find这个函数  这个函数返回子字符串首次出现的位置,那么有人会这样写

    string str1 = "";
if(str1.find("aaaa") >= )
cout<<"有"<<endl;
else
cout<<"没有"<<endl; system("pause");
return ;

结果输出是错误的。而实际上必须写成这样

    string str1 = "";
if(str1.find("aaaa") != string::npos)
cout<<"有"<<endl;
else
cout<<"没有"<<endl;

经过调试发现 find的返回值是无符号整型,也就是说没有负数。>= 0 在任何时刻都成立的。