npos经常和find一起用~它们两个都在头文件<string>里面~先看用法:
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <string> using namespace std; int main() { string s = "abc"; if (s.find("b") != string::npos) printf("字符串s中存在b字符~"); else printf("字符串s中不存在b字符~"); return 0; } |
简单点说就是,在字符串s中查找“b”字符(当然也可以查找一个字符串如“ab”),find函数如果找到了,就会返回第一次出现这个字符的位置,如果没找到怎么办呢,它会返回npos这个位置,npos本质上其实是一个常数,一般来说值是-1,所以s.find(“b”) != string::npos表示找到了“b”这个字符~如果相等就是没找到的意思啦~
我们可以从C++库函数的官方文档(www.cplusplus.com)中找到对这两个函数的解释~
std::string::find——[Return Value]
The position of the first character of the first match.
If no matches were found, the function returns string::npos.std::string::npos
static const size_t npos = -1;
As a return value, it is usually used to indicate no matches.
以及关于为什么npos的值是-1的解释:
npos is a static member constant value with the greatest possible value for an element of type size_t.
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.
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼