谷动谷力

 找回密码
 立即注册
查看: 412|回复: 0
打印 上一主题 下一主题
收起左侧

C++ string::npos 㳀析

[复制链接]
跳转到指定楼层
楼主
发表于 2023-8-16 10:14:29 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
C++  string::npos 㳀析

1. 关于npos的定义
string::npos 是一个静态成员常量,表示 size_t 的最大值;
size_t 的详细讲解
该值表示“直到字符串结尾”,作为返回值它通常被用作表明没有匹配;
string::npos 的定义:
static const size_type npos = -1;

2. 使用方法
要想判断 find() 的结果是否为 npos,最好的办法是直接比较。比如:
if (str.find("abc") == string::npos) {
        ...
}

3. 注意事项
int index = str.find("abc");  
if (index == string::npos)  
  ...

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

4. 证明:-1 表示 size_t 的最大值
#include <iostream>
#include <limits>
#include <string>
using namespace std;

int main()
{
    size_t npos = -1;

        // X86:npos: 4294967295
    // x64:npos: 18446744073709551615
    cout << "npos: " << npos << endl;

        // X86:size_t max: 4294967295
    // x64:size_t max : 18446744073709551615
    cout << "size_t max: " << numeric_limits<size_t>::max() << endl;

    return 0;
}
可见,它们是相等的,也就是说 npos 表示 size_t 的最大值。

+10
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|深圳市光明谷科技有限公司|光明谷商城|Sunshine Silicon Corpporation ( 粤ICP备14060730号|Sitemap

GMT+8, 2024-5-15 01:00 , Processed in 0.110752 second(s), 47 queries .

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表