【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的查找函数

  1. find
  2. rfind
  3. find_first_of
  4. find_first_not_of
  5. find_last_of
  6. 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

 


posted @   opensmarty  阅读(187)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示