【发布时间】:2011-07-03 01:07:27
【问题描述】:
以下语句是什么意思?
string s="Joe Alan Smith"";
cout << (s.find("Allen") == string::npos) << endl;
【问题讨论】:
标签: c++
以下语句是什么意思?
string s="Joe Alan Smith"";
cout << (s.find("Allen") == string::npos) << endl;
【问题讨论】:
标签: c++
其实string::find()返回的是找到的字符串的位置,但是如果没有找到给定的字符串,则返回string::npos,其中npos表示没有位置。
npos 是一个无符号整数值,标准将其定义为-1(有符号表示),表示没有位置。
//npos is unsigned, that is why cast is needed to make it signed!
cout << (signed int) string::npos <<endl;
输出:
-1
见 Ideone:http://www.ideone.com/VRHUj
【讨论】:
string::size_type(-1)。
http://www.cplusplus.com/reference/string/string/npos/
作为返回值,通常用于表示失败。
换句话说,如果在给定的字符串s中找不到字符串'Allen',则打印出来。
【讨论】:
.find() 方法如果在搜索字符串中没有找到目标字符串,则返回 string::npos。它是一个整数,其值不能表示“找到”的索引值,通常为 -1。有效的索引值是一个 >= 0 的整数,它表示找到目标字符串的索引。
【讨论】: