一、关于npos的定义
string::npos是一个静态成员常量,表示size_t的最大值(Maximum value for size_t)。该值表示“直到字符串结尾”,作为返回值它通常被用作表明没有匹配。
string::npos是这样定义的:
static const size_type npos = -1;
因为string::size_type描述的是size,故需为无符号整数型类别。因为缺省配置为size_t作为size_type,于是-1被转换为无符号整数类型,npos也就成为了该类别的最大无符号值。不过实际值还是取决于size_type的实际定义类型,即无符号整型(unsigned int)的-1与无符号长整型(unsigned long)的-1是不同的。
如果对 -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;
}
二、实例
配合string::find()函数使用
string::find()函数:是一个字符或字符串查找函数,该函数有唯一的返回类型,即string::size_type,即一个无符号整形类型,可能是整数,也可能是长整数。如果查找成功,返回按照查找规则找到的第一个字符或者子串的位置;如果查找失败,返回string::npos,即-1(当然打印出的结果不是-1,而是一个很大的数值,那是因为它是无符号的)。
举个例子
#include <iostream>
#include <limits>
#include <string>
std::string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
void result(const char* p)
{
std::string::size_type position = s.find(p);
if ( position != std::string::npos )
{
std::cout << "Position is : " << position << std::endl;
}
else{
std::cout << "Not found." << std::endl;
}
}
int main()
{
result("jk");
result("b3");
return 0;
}
参考:
https://www.cnblogs.com/lixuejian/p/10844905.html
https://blog.csdn.net/weixin_38736371/article/details/82972953