static const size_type npos = -1;//定义
The constant is the largest representable value of type size_type. It is assuredly larger than max_size(); hence it serves as either a very large value or as a special code.
- #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的最大值
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string b;
- getline(cin,b);
- int count=0;
- for(int i=0;i<=127;i++)
- if(b.find(i)!=string::npos)
- count++;
- cout<<count;
- }
- string name("Annaqijiashe");
- int pos=name.find("Anna");
- if(pos==string::npos)
- cout<<"Anna not found!\n";
- else cout<<"Anna found at pos:"<<pos<<endl;
- tmpname.replace(idx+1, string::npos, suffix);
- #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
- int idx = str.find("abc");
- if (idx == string::npos)
- ...
if (str.find("abc") == string::npos) { ... }
2、string 类提供了 6 种查找函数,每种函数以不同形式的 find 命名。这些操作全都返回 string::size_type 类型的值,以下标形式标记查找匹配所发生的位置;或者返回一个名为 string::npos 的特殊值,说明查找没有匹配。string 类将 npos 定义为保证大于任何有效下标的值。
参考资料:
3014



被折叠的 条评论
为什么被折叠?



