打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
关于string::find的返回值

#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

 

下面来看MSDNsize_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 不同(前提是两者型别大小不同)。

0
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
std::string::find() 和 std::string::npos
STL[12]string使用总结
String 字符串 | 赖明星
图像处理调试(二十六)
size
比较string对象及其+操作 79
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服