[C++基础] string::npos 是什么

string::npos 是 C++ 标准库中的 std::string 类的一个静态成员常量。其值通常设置为最大的 size_t 值,表示一个不可能在字符串中出现的位置。它常常用于 std::string 类的成员函数,如 find(), rfind(), find_first_of(), find_last_of() 等,来指示未找到子字符串或字符的位置。

例如,当使用 find() 函数在字符串中搜索某个子字符串时,如果该函数没有找到目标子字符串,它会返回 string::npos

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    size_t position = s.find("World");
    
    if (position != std::string::npos) { // 不等于,就是找到了
        std::cout << "Found 'World' at position: " << position << std::endl;
    } else {
        std::cout << "'World' not found in the string." << std::endl;
    }

    position = s.find("Earth");
    if (position == std::string::npos) { // 等于 npos 就是没找到
        std::cout << "'Earth' not found in the string." << std::endl;
    }

    return 0;
}

输出

Found 'World' at position: 7
'Earth' not found in the string.

关于这个 npos ,我一般记为 no position,表示没有这个串的位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值