string::npos的一些说明

来源:互联网 发布:嵌入式linux打开图片 编辑:程序博客网 时间:2024/04/30 11:55

string::npos的一些说明


一、定义

std::string::npos的定义:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static const size_t npos = -1;  

表示size_t的最大值(Maximum value for size_t,如果对 -1表示size_t的最大值有疑问可以采用如下代码验证:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <limits>  
  3. #include <string>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     size_t npos = -1;  
  9.     cout << "npos: " << npos << endl;  
  10.     cout << "size_t max: " << numeric_limits<size_t>::max() << endl;  
  11. }  

在我的PC上执行结果为:

                 npos:           4294967295

                 size_t max:  4294967295

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


二、使用

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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <limits>  
  3. #include <string>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     string filename = "test";  
  9.     cout << "filename : " << filename << endl;  
  10.   
  11.     size_t idx = filename.find('.');   //作为return value,表示没有匹配项  
  12.     if(idx == string::npos)      
  13.     {  
  14.         cout << "filename does not contain any period!" << endl;  
  15.     }  
  16. }  

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

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. tmpname.replace(idx+1, string::npos, suffix);  

这里的string::npos就是一个长度参数,表示直到字符串的结束,配合idx+1表示,string的剩余部分。

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <limits>  
  3. #include <string>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     string filename = "test.cpp";  
  9.     cout << "filename : " << filename << endl;  
  10.   
  11.     size_t idx = filename.find('.');   //as a return value  
  12.     if(idx == string::npos)      
  13.     {  
  14.         cout << "filename does not contain any period!" << endl;  
  15.     }  
  16.     else  
  17.     {  
  18.         string tmpname = filename;  
  19.         tmpname.replace(idx + 1, string::npos, "xxx"); //string::npos作为长度参数,表示直到字符串结束  
  20.         cout << "repalce: " << tmpname << endl;  
  21.     }  
  22. }  
0 0
原创粉丝点击