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!
相关推荐
你怎么知道我是队长6 分钟前
C语言---输入和输出
c语言·开发语言
net3m339 分钟前
单片机屏幕多级菜单系统之当前屏幕号+屏幕菜单当前深度 机制
c语言·c++·算法
mmz12079 分钟前
二分查找(c++)
开发语言·c++·算法
你怎么知道我是队长16 分钟前
C语言---文件读写
java·c语言·开发语言
陌路2017 分钟前
C++30 STL容器 -deque双端队列
开发语言·c++
AI视觉网奇21 分钟前
ue 自己制作插件 c++
c++·ue5
咕白m62524 分钟前
通过 C# 快速生成二维码 (QR code)
后端·.net
踏浪无痕30 分钟前
架构师如何学习 AI:三个月掌握核心能力的务实路径
人工智能·后端·程序员
xb113235 分钟前
C#委托详解
开发语言·c#
brent42336 分钟前
DAY50复习日
开发语言·python