【贪玩巴斯】带你学:C++ tips ——知识点:string::npos 用法详细解析 , 看这一篇就够了 2021年12月21日

欢迎关注我的微信公众号:
编程之蓁

ID:
bianchengzhizhen
及时分享算法、计算机科学以及游戏编程内容

本人CSDN博客主页:
https://blog.csdn.net/D16100?spm=1000.2115.3001.5343&type=blog
欢迎互相交流学习
————————————————

一、定义

std::string::npos的定义:
static const size_t npos = -1;
表示size_t的最大值(Maximum value for size_t)

在MSDN中有如下说明:
basic_string::npos
static const size_type npos = -1;//定义

以上的意思是npos是一个常数,表示size_t的最大值(Maximum value for size_t)。
许多容器都提供这个东西,用来表示不存在的位置,类型一般是std::container_type::size_type。

例子说明:

#include <iostream>
#include <limits>
#include <string>
using namespace std;
 
int main()
{
    size_t npos = -1;
    cout << "npos: " << npos << endl;
    cout << "size_t max: " << numeric_limits<size_t>::max() << endl;
}

执行结果为:

             npos:           4294967295

             size_t max:  4294967295

可见他们是相等的,也就是说npos表示size_t的最大值

二、使用

1.如果作为一个返回值(return value)表示没有找到匹配项

如果作为一个返回值(return value)表示没有找到匹配项

例子说明:

#include <iostream>
#include <limits>
#include <string>
using namespace std;
 
int main()
{
    string filename = "test";
    cout << "filename : " << filename << endl;
 
    size_t idx = filename.find('.');   //作为return value,表示没有匹配项
    // 此处使用方法!!!
    if(idx == string::npos)
    {
        cout << "filename does not contain any period!" << endl;
    }
}

2.但是string::npos作为string的成员函数的一个长度参数时,表示“直到字符串结束(until the end of the string)”

但是string::npos作为string的成员函数的一个长度参数时,表示“直到字符串结束(until the end of the string)”

举例说明:


#include <iostream>
#include <limits>
#include <string>
using namespace std;
 
int main()
{
    string filename = "test.cpp";
    cout << "filename : " << filename << endl;
 
    size_t idx = filename.find('.');   //as a return value
    if(idx == string::npos)    
    {
        cout << "filename does not contain any period!" << endl;
    }
    else
    {
        string tmpname = filename;
        tmpname.replace(idx + 1, string::npos, "xxx"); //string::npos作为长度参数,表示直到字符串结束
        cout << "repalce: " << tmpname << endl;
    }
}

执行结果:

filename:test.cpp

replace: test.xxx

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贪玩巴斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值