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!
相关推荐
多加点辣也没关系3 小时前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
考虑考虑4 小时前
tcpdump指令
运维·后端·自动化运维
Resean02234 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
Wellijohn4 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
皮皮林5515 小时前
YouTube 是如何保存巨量视频文件的?
后端
学长毕设5 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
码途行者5 小时前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
23图5 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
feixing_fx6 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
无奈笑天下6 小时前
Linux上kdump故障标准处理流程
linux·运维·服务器·github