【c&c++】std::string::npos的使用
std::string::npos
std::string::npos是一个常数,它等于size_type类型可以表示的最大值,用来表示一个不存在的位置,类型一般是std::container_type::size_type。
定义
static const size_type npos = -1;
#include <iostream> int main(int argc, char *argv[]) { size_t a = -1; std::cout << "a : " << a << std::endl; std::cout << "npos : " << std::string::npos << std::endl; std::cout << "size_type max : " << std::numeric_limits<std::string::size_type>::max() << std::endl; std::cout << "size_t max : " << std::numeric_limits<size_t>::max() << std::endl; std::cout << "uint64_t max : " << std::numeric_limits<uint64_t>::max() << std::endl; return 0; }
执行结果
a : 18446744073709551615 npos : 18446744073709551615 size_type max : 18446744073709551615 size_t max : 18446744073709551615 uint64_t max : 18446744073709551615
使用
std::string的查找函数
- find
- rfind
- find_first_of
- find_first_not_of
- find_last_of
- find_last_not_of
这些操作全都返回 string::size_type 类型的值。
example
#include <iostream> int main(int argc, char *argv[]) { std::string const s = "This is a string"; std::string::size_type n1 = s.find("is"); if (std::string::npos == n1) { std::cout << "not found is" << std::endl; } else { std::cout << "index : " << n1 << std::endl; } std::string::size_type n2 = s.find("oo"); if (std::string::npos == n2) { std::cout << "not found oo" << std::endl; } else { std::cout << "index : " << n2 << std::endl; } return 0; }
执行结果
index : 2 not found oo
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界