现在的位置: 首页 > 综合 > 正文

使用std::string::find() 和 std::string::npos需要注意的地方

2013年10月01日 ⁄ 综合 ⁄ 共 589字 ⁄ 字号 评论关闭
int pos = str.find("\t");

if (pos == string::npos)
上述代码中,pos 的类型被定义为 int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。

c++中 npos 是这样定义的:

static const size_type npos = -1;

因为 string::size_type (由字符串配置器 allocator 定义) 描述的是 size,故需为无符号整数。因为缺省配置器以型别 size_t 作为 size_type,于是 -1 被转换为无符号整数,npos 也就成了该型别的最大无符号值。不过实际数值还是取决于 size_type 的实际定义。不幸的是这些最大值都不相同。事实上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是两者型别大小不同)。因此,比较式 pos == string::npos
中,如果 pos的值为-1,由于 pos 和字符串 string::npos 型别不同,比较结果可能得到 false。

要想判断 find() 的结果是否为 string::npos,最好的办法是直接比较:

 
if (str.find("\t") == string::npos) { … }

转载自:http://www.cppblog.com/ming81/archive/2011/04/15/144290.html

抱歉!评论已关闭.