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!
相关推荐
破茧蝴蝶5 小时前
Python分布式爬虫完整教程
开发语言·python
大哥您好5 小时前
QEMU 11.1.2 多架构编译指南(x86_64 / aarch64 / riscv64)
linux·服务器
狗凯之家源码网5 小时前
全新 PHP 轻量客服聊天室源码深度评测
开发语言·php·聊天室系统
凤山老林5 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
远离UE45 小时前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
keyipatience6 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
一拳一个呆瓜6 小时前
【STL】文件系统导航
c++·stl
朱涛的自习室6 小时前
我给 Gemini 4 和 DeepSeek 搞了套「末位淘汰」,AI 干活会更猛吗?(Day 3)
android·前端·后端
All for pursuit.6 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
Gauss松鼠会6 小时前
高斯数据库(openGauss)的物理存储结构
运维·服务器·数据库·sql·opengauss·经验总结