string::npos
是 C++ 标准库中的 std::string
类的一个静态成员常量。其值通常设置为最大的 size_t 值,表示一个不可能在字符串中出现的位置。它常常用于 std::string 类的成员函数,如 find()
, rfind()
, find_first_of()
, find_last_of()
等,来指示未找到子字符串或字符的位置。
例如,当使用 find()
函数在字符串中搜索某个子字符串时,如果该函数没有找到目标子字符串,它会返回 string::npos
。
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, World!";
size_t position = s.find("World");
if (position != std::string::npos) { // 不等于,就是找到了
std::cout << "Found 'World' at position: " << position << std::endl;
} else {
std::cout << "'World' not found in the string." << std::endl;
}
position = s.find("Earth");
if (position == std::string::npos) { // 等于 npos 就是没找到
std::cout << "'Earth' not found in the string." << std::endl;
}
return 0;
}
输出
Found 'World' at position: 7
'Earth' not found in the string.
关于这个 npos ,我一般记为 no position,表示没有这个串的位置