一、std::string::npos 概述
-
std::string::npos是一个静态常量,表示size_t类型的最大值 -
std::string::npos用于表示字符串操作中的未找到的位置或无效位置 -
std::string::npos属于 C++ 标准库中的<string>头文件
二、std::string::npos 的作用
std::string::npos表示size_t类型的最大值
c++
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << string::npos << endl;
return 0;
}
# 输出结果
18446744073709551615
- 在字符串查找中,例如,
find()、rfind()、find_first_of()等,如果查找失败,函数会返回std::string::npos表示未找到目标子串或字符
| 函数 | 说明 |
|---|---|
find() |
正向查找子串 |
rfind() |
反向查找子串 |
find_first_of() |
查找字符集合中的任意一个字符,返回第一个匹配的位置 |
c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
size_t found = str.find("Python");
if (found == string::npos) {
cout << "not found" << endl;
}
return 0;
}
# 输出结果
not found
- 在
substr()、erase()中,std::string::npos表示直到字符串末尾
c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
string substr = str.substr(7, string::npos);
cout << substr << endl;
return 0;
}
# 输出结果
world!