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!
相关推荐
头发还没掉光光2 小时前
C++STL之list
c语言·数据结构·c++·list
Terio_my2 小时前
Java bean 数据校验
java·开发语言·python
Tony Bai2 小时前
【Go开发者的数据库设计之道】07 诊断篇:SQL 性能诊断与问题排查
开发语言·数据库·后端·sql·golang
Elastic 中国社区官方博客3 小时前
Elasticsearch MCP 服务器:与你的 Index 聊天
大数据·服务器·人工智能·elasticsearch·搜索引擎·ai·全文检索
超级大只老咪3 小时前
何为“类”?(Java基础语法)
java·开发语言·前端
cpsvps_net3 小时前
VPS服务器锁等待超时处理,如何有效解决数据库性能瓶颈
服务器·数据库·oracle
花花鱼3 小时前
spring boot项目使用tomcat发布,也可以使用Undertow(理论)
spring boot·后端·tomcat
我笑了OvO3 小时前
C++类和对象(1)
java·开发语言·c++·类和对象
_屈臣_5 小时前
卡特兰数【模板】(四个公式模板)
c++·算法
你的人类朋友5 小时前
快速搭建redis环境并使用redis客户端进行连接测试
前端·redis·后端