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


--------------------- 
作者:幻想之漁 
來源:CSDN 
原文:https://blog.csdn.net/lmb1612977696/article/details/81455708 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章