string中的npos

STL中的string.find()函数原型如下:

size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_type n) const;
size_t find (char c, size_t pos = 0) const noexcept;

其返回值都是一个size_t类型的。
如果找到就返回该字符或者字符串的下标,如果没找到呢?
STL内使用npos位来标志没找到,先来看看官方如何解释这个变量:

std::string::npos
static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

中文:
size_t的最大值
npos是一个静态成员常量值,其值为size_t类型的元素的最大可能值。

这个值用作字符串成员函数中len(或sublen)参数的值时,意思是“直到字符串结束”。 作为返回值,通常用于表示不匹配。 此常量的值为-1,这是因为size_t是无符号整型,它是此类型最大的可表示值。

使用如下:

std::string s1 = "hello world!";
if(s1.find('o') != std::string::npos){
    std::cout<<"找到字母o"<<    std::endl;
}else{
    std::cout<<"没有找到字母o"<<  std::endl;
}

猜你喜欢

转载自blog.csdn.net/qq_36528114/article/details/80828240