string::npos的一些说明
来源:互联网 发布:嵌入式linux打开图片 编辑:程序博客网 时间:2024/04/30 11:55
string::npos的一些说明
一、定义
std::string::npos的定义:
- static const size_t npos = -1;
表示size_t的最大值(Maximum value for size_t),如果对 -1表示size_t的最大值有疑问可以采用如下代码验证:
- #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;
- }
在我的PC上执行结果为:
npos: 4294967295
size_t max: 4294967295
可见他们是相等的,也就是说npos表示size_t的最大值
2.1 如果作为一个返回值(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.2 但是string::npos作为string的成员函数的一个长度参数时,表示“直到字符串结束(until the end of the string)”。例如:
- tmpname.replace(idx+1, string::npos, suffix);
这里的string::npos就是一个长度参数,表示直到字符串的结束,配合idx+1表示,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;
- }
- }
0 0
- string::npos的一些说明
- string::npos的一些说明
- string::npos的一些说明
- string::npos的一些说明
- string::npos的大小
- C++中string::npos的一些用法总结
- C++中string::npos的一些用法总结
- string::npos
- string::npos
- string::npos
- string::npos
- string::npos
- string::npos
- string::npos
- string::npos
- string::npos
- find 函数和string :: npos 的用法
- string::npos表示不存在的位置
- C++学习心得(5)继承与派生
- 2012年5月SAT香港真题解析
- Android开发模板------ViewPager(二)FragmentPagerAdapter的简介
- 在多个页面中地方需要登录,创建一个新的navgationController
- ABAP 在程序中启动后台JOB
- string::npos的一些说明
- 学习J2ME需要掌握的七种技术
- Android面试题
- 设计模式——装饰者模式
- getFragmentManager与getChildFragmentManager
- Java Generics Quick Tutorial
- SpringMVC 通过注解进行参数注入
- 消息队列函数(msgget、msgctl、msgsnd、msgrcv)及其范例
- CAShapeLayer的简介以及基本使用