关于string::find()的返回值(转)

来源:互联网 发布:ubuntu 没有文件夹权限 编辑:程序博客网 时间:2024/06/06 02:54

#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
     std::string szHello = "hello,world!";

     if( szHello.find("hi")>= 0)
          std::cout<<"hi is exist!"<<std::endl;
     else
          std::cout<<"hi is not exist!"<<std::endl;
     return 0;
}

上述程序,运行结果为:hi is exist!

若将代码更改为: int nResult =   szHello.find("hi");

                          if(nResult >= 0)

则运行结果为:hi is not exist!

为什么会出现这样的结果呢?究其原因是string::find的返回值为string::size_type类型,其值为string::npos。

下面来看MSDN对size_type的定义:
basic_string::size_type:An unsigned integer type that can represent the number of elements and indices in a string.
可见size_type实际上就是一个无符号整型(unsigned int),所以与整型进行比较是完全可以的。不过C,C++在有符号数和无符号数之间的运算时,会先把数都转成无符号数,再运算,因此,如果i=-1,那么转成无符号数就是0xFFFFFFFF,就会出现-1>2这样的情况,所以VC对这种情况会有warning,提醒你注意。这也就是会出现上述状况的本质原因。


要修改程序其实很简单,将上面的0换为0xFFFFFFFF或者string::npos即可解决。

要想判断 find() 的结果是否为npos,最好的办法是直接比较:
if (szHello.find("hi") == string::npos) { ... }


PS:

npos 是这样定义的:
static const size_type npos = -1;

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


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kinghui_1986/archive/2010/05/06/5563874.aspx