赞
踩
欢迎关注我的微信公众号:
编程之蓁
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
- 1
- 2
- 3
可见他们是相等的,也就是说npos表示size_t的最大值
如果作为一个返回值(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; } }
但是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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。