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

栏目: C++ · 发布时间: 7年前

内容简介:npos经常和find一起用~它们两个都在头文件<string>里面~先看用法:简单点说就是,在字符串s中查找“b”字符(当然也可以查找一个字符串如“ab”),find函数如果找到了,就会返回第一次出现这个字符的位置,如果没找到怎么办呢,它会返回npos这个位置,npos本质上其实是一个常数,一般来说值是-1,所以s.find(“b”) != string::npos表示找到了“b”这个字符~如果相等就是没找到的意思啦~我们可以从C++库函数的官方文档(www.cplusplus.com)中找到对这两个函

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.

❤❤点击这里 -> 订阅PAT、GPLT天梯赛、LeetCode题解离线版❤❤ [C++] STL库函数之字符串string::npos的介绍,以及string中的find函数~

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Effective JavaScript

Effective JavaScript

David Herman / Addison-Wesley Professional / 2012-12-6 / USD 39.99

"It's uncommon to have a programming language wonk who can speak in such comfortable and friendly language as David does. His walk through the syntax and semantics of JavaScript is both charming and h......一起来看看 《Effective JavaScript》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具