string的find()与npos

在 C++ 中,std::string::find() 是一个用于在字符串中查找子字符串或字符的成员函数。查找成功时返回匹配的索引位置,查找失败时返回 std::string::npos,表示未找到。

std::string::find() 函数原型

std::size_t find(const std::string& str, std::size_t pos = 0) const noexcept;
std::size_t find(const char* s, std::size_t pos = 0) const;
std::size_t find(char c, std::size_t pos = 0) const noexcept;

参数说明

  1. str/s:要查找的子字符串或字符。
  2. pos(可选):从哪个位置开始查找,默认为 0,即从字符串的开始位置查找。
  3. 返回值:查找成功时返回第一个匹配字符的索引,查找失败时返回 std::string::npos

std::string::npos

std::string::npos 是一个常量,表示查找操作失败或子字符串不存在时的返回值。具体定义为 std::string::npos = -1,它实际上是一个 std::size_t 类型的最大值。

示例

以下是一些简单的示例,演示如何使用 std::string::find()std::string::npos

查找子字符串

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 查找子字符串 "World"
    std::size_t found = str.find("World");
    if (found != std::string::npos) {
        std::cout << "Found 'World' at index: " << found << std::endl; // 输出: Found 'World' at index: 7
    } else {
        std::cout << "'World' not found." << std::endl;
    }

    // 查找不存在的子字符串 "Earth"
    found = str.find("Earth");
    if (found == std::string::npos) {
        std::cout << "'Earth' not found." << std::endl; // 输出: 'Earth' not found.
    }

    return 0;
}

查找字符

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 查找字符 'o'
    std::size_t found = str.find('o');
    if (found != std::string::npos) {
        std::cout << "Found 'o' at index: " << found << std::endl; // 输出: Found 'o' at index: 4
    }

    return 0;
}

从指定位置开始查找

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 从索引 5 开始查找字符 'o'
    std::size_t found = str.find('o', 5);
    if (found != std::string::npos) {
        std::cout << "Found 'o' at index: " << found << std::endl; // 输出: Found 'o' at index: 8
    }

    return 0;
}

总结

  • std::string::find():用于查找字符串或字符。返回子字符串第一次出现的索引,或者返回 std::string::npos 表示未找到。
  • std::string::npos:表示查找操作失败时的返回值(通常为最大值 -1 表示无效位置)。
posted @   牛马chen  阅读(685)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示