关于string::find的返回值
来源:互联网 发布:mathlab 矩阵使用 编辑:程序博客网 时间:2024/06/03 18:08
#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 不同(前提是两者型别大小不同)。
- 关于string::find的返回值
- 关于string::find()的返回值(转)
- 关于c++ find返回值类型 与string::nops的使用的若干问题
- std::string的find返回值为string::size_type
- HibernateTemplate的find(String querystring)返回值详解
- string类find函数返回值判定
- 为什么 string.find()返回值是-1
- string类find函数返回值判定
- string类find函数返回值判定
- C++ string.find()返回值问题
- string的find函数返回值和string::npos 的理解
- 关于string类的find()一系列函数
- c++和python string 的find()方法的返回值不同
- string的find函数,返回下标,当不存在时返回string::npos,为无符号数最大值
- lua 脚本 string.find 查找关于 ( ) 的问题
- 关于 ++ 的返回值
- 关于EditText中的getText()方法的返回值类型以及string的转换问题
- 关于C++调用C#封装的dll后,获取C#中string返回值的问题
- Mini2440 串口 KITL使用问题汇总
- Linux sysctl.conf 优化方案
- Oracle中的归档日志(Archive Log)
- js 输入的css 等内容
- 完成端口模型IOCP详解 (一)
- 关于string::find的返回值
- ActiveMQ中如何发送/接受Object(Serializable)实例的示例演示
- Android Building System 分析
- (转)比尔盖茨说过的十条“金玉良言”
- dspace windows oracle install
- doc转pdf实用程序
- Designer8.5.1中的代码引入引出
- 三字经英文翻译
- vimrc on May 6th,2010