当前位置:   article > 正文

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

std::string::npos

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

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

执行结果为:

             npos:           4294967295

             size_t max:  4294967295
  • 1
  • 2
  • 3

可见他们是相等的,也就是说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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

执行结果:

filename:test.cpp

replace: test.xxx

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/280668
推荐阅读
相关标签
  

闽ICP备14008679号