C++ - 标准库之 <string> npos(npos 概述、npos 的作用)

一、std::string::npos 概述

  1. std::string::npos 是一个静态常量,表示 size_t 类型的最大值

  2. std::string::npos 用于表示字符串操作中的未找到的位置或无效位置

  3. std::string::npos 属于 C++ 标准库中的 <string> 头文件


二、std::string::npos 的作用

  1. std::string::npos 表示 size_t 类型的最大值
c++ 复制代码
#include <iostream>
#include <string>

using namespace std;

int main() {

	cout << string::npos << endl;

	return 0;
}
复制代码
# 输出结果

18446744073709551615
  1. 在字符串查找中,例如,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
  1. 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!
相关推荐
yqcoder几秒前
uni-app 之 下拉刷新
运维·服务器·uni-app
mancy_1212123 分钟前
复古C语言代码复活!——以121+hello.c为例摘要
c语言·vscode·gitee·visual studio·新人首发·turbo c
rosmis8 分钟前
地铁病害检测系统软件改进记录-2-02
开发语言·前端·javascript
huohaiyu14 分钟前
IP协议详解
服务器·网络·tcp/ip
进击的小头17 分钟前
FIR滤波器实战:音频信号降噪
c语言·python·算法·音视频
欧阳x天21 分钟前
STL详解(九)—— stack和queue的模拟实现
开发语言·c++
xqqxqxxq21 分钟前
洛谷算法1-1 模拟与高精度(NOIP经典真题解析)java(持续更新)
java·开发语言·算法
沐知全栈开发27 分钟前
Rust 函数
开发语言
Madison-No732 分钟前
【Linux】一切皆文件的理解 && 缓冲区 && 简易设计libc库
linux·运维·服务器
Alaaaaaaan36 分钟前
[DevOps]使用github-action工具部署docker容器(实现提交代码一键推送部署到服务器)
服务器·前端·docker·容器·github