今天的在LeetCode上做到 验证IP地址 时发现官方解答里有这么一段cur == string::npos,突然发现完全没有印象。
一言以蔽之,string::npos的大小与size_t max(size_t的最大值)一致,为4294967295。string 类将 npos 定义为保证大于任何有效下标的值。如果cur == string::npos,那就说明没有匹配到。主要用在find()上
如果是将string::npos作为string的成员函数的一个长度参数(例如 replace()),它就表示“直到字符串结束”
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
string filename = "test.cpp";
cout << "filename : " << filename << endl;
size_t cur = filename.find('.');//查找有没有.
string tmp = filename;
tmp.replace(cur+ 1, string::npos, "xxx"); //也就是说从cur+1(.的后面),到字符串末尾位置替换为xxx
cout << "repalce: " << tmp << endl;
return 0;
}
它的结果应该是:
filename:test.cpp
replace: test.xxx
string 类总共提供了 6 种查找函数,每种函数以不同形式的 find 命名。这些操作全都返回 string::size_type 类型的值。这是C++11中的内容,然而我以前却没用过。只能说,C++的学习和算法复健的路还长着呢