下面的结果是什么?
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string s = "abc";
- if(s.find("x"))
- {
- cout << "yes" << endl;
- }
- else
- {
- cout << "no" << endl;
- }
- return 0;
- }
结果是:yes,因为s.find("x")的结果是(U32)(-1), 是一个很大的数,字符串查找时需要与s.npos进行比较。
if语句改为下面的就可以了:
if (s.npos != s.find("x"))

本文通过一个简单的C++示例程序介绍了如何使用std::string的find方法来查找子字符串,并解释了find方法返回值的含义及其如何影响if条件判断的结果。
205

被折叠的 条评论
为什么被折叠?



