string.find()与string::npos


C++: string 中find函数的用法以及string::npos的含义_linwh8的博客-CSDN博客_c++ npos

查找字符串a是否包含子串b,不是用strA.find(strB) > 0 而是 strA.find(strB) != string:npos

其中string:npos是个特殊值,说明查找没有匹配

先说说string::npos参数:
npos 是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 许多容器都提供这个东西。取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。
再来说说find函数:
find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos。
if (a.find(b) != string::npos)

{

cout << "Yes!" << endl;

}

else { cout << "No!" << endl;

}

猜你喜欢

转载自blog.csdn.net/jusu10/article/details/120779132