原
cppman std::string::npos
std::string::npos(3) C++ Programmer's Manual std::string::npos(3)
NAME
std::string::npos - Maximum value for size_t //size_t 的最大值
TYPE
public static member constant //公共静态成员常量
SYNOPSIS
#include <string>
static const size_t npos = -1;
DESCRIPTION
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.
//npos 是一个静态成员常量值,对于 size_t 类型的元素具有最大可能值。
//此值在用作字符串成员函数中的 len(或 sublen)参数的值时,表示“直到字符串的结尾”。
//作为返回值,它通常用于表示不匹配。
//此常量定义为值 -1,因为 size_t 是无符号整数类型,所以它是该类型的最大可能表示值。
REFERENCE
cplusplus.com, 2000-2015 - All rights reserved.
cplusplus.com 2022-05-13 std::string::npos(3)
std::string::npos(3) C++ Programmer’s Manual std::string::npos(3)
NAME
std::string::npos - Maximum value for size_t //size_t 的最大值
TYPE
public static member constant //公共静态成员常量
SYNOPSIS
#include
static const size_t npos = -1;
DESCRIPTION
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.
//npos 是一个静态成员常量值,对于 size_t 类型的元素具有最大可能值。
//此值在用作字符串成员函数中的 len(或 sublen)参数的值时,表示“直到字符串的结尾”。
//作为返回值,它通常用于表示不匹配。
//此常量定义为值 -1,因为 size_t 是无符号整数类型,所以它是该类型的最大可能表示值。
REFERENCE
cplusplus.com, 2000-2015 - All rights reserved.
cplusplus.com 2022-05-13 std::string::npos(3)
20230814:C++ std::string::npos 解析
介绍
在C++标准库中,std::string::npos
是一个静态常量值,定义在std::basic_string
类型中。该常量表示的是一种特殊情况,即不存在的位置或者搜索失败。其实际数值等于字符串最大长度的最大值,通常是 -1
(由于内部使用无符号整数存储,因此实际值为最大的无符号整数)。
static const size_type npos = -1;
这个常量在字符串操作中非常有用,可以帮助我们检测到某些字符串函数(如 find
, rfind
, find_first_of
, find_last_of
, find_first_not_of
, find_last_not_of
等)是否找到了期望的结果。
使用 std::string::npos
当使用std::string
类中的搜索函数时,如果未能找到指定的字符或字符串,函数将返回std::string::npos
。
例如,在以下代码中:
std::string str = "Hello, World!";
size_t found = str.find("Earth");
if (found == std::string::npos) {
std::cout << "Substring not found." << std::endl;
} else {
std::cout << "Substring found at position: " << found << std::endl;
}
由于 “Earth” 并不在 “Hello, World!” 中,所以 str.find("Earth")
返回 std::string::npos
,输出 “Substring not found.”。
注意事项
值得注意的是,虽然 std::string::npos
的实际值通常为 -1
,但不能直接将它与 -1
进行比较。因为 std::string::npos
的类型为 std::string::size_type
,它是一个无符号整数类型,而 -1
是有符号的。如果你试图将 std::string::npos
与 -1
进行比较,编译器可能会产生警告。因此,总是推荐使用 std::string::npos
而不是 -1
来进行字符串搜索结果的判断。