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!
相关推荐
ClouGence1 小时前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
Gopher_HBo2 小时前
Go语言学习笔记(十二)Tcp实现Rpc
后端
夜悊2 小时前
C++代码示例:进制数简单生成工具
c++
糖拌西瓜皮2 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
雪隐2 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地claude code编程助理
人工智能·后端
AskHarries2 小时前
Browser Tool:网页打开、点击、输入、截图和验证
后端
程序员cxuan2 小时前
分享一下我最近常用的 10 个 Codex 小技巧。
人工智能·后端·程序员
一线大码2 小时前
Smart-Doc 的简单使用
java·后端·restful
喵个咪3 小时前
技术复盘:基于 go-wind-cms 的官网+商城双业务渐进拆分实战
后端·架构·go
ZengLiangYi3 小时前
批量导入 1000 条对话的性能优化实战
javascript·后端·架构