[C++] STL库函数之字符串string::npos的介绍,以及string中的find函数~

npos经常和find一起用~它们两个都在头文件<string>里面~先看用法:

#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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值