std::string::npos的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lmb1612977696/article/details/81455708

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

猜你喜欢

转载自blog.csdn.net/lmb1612977696/article/details/81455708