【C++】C++中的find方法介绍

目录

一.find方法基本用法

1.查找字符

2.查找子字符串

3.查找子字符串(从指定位置开始)

4.查找字符范围

5.查找不包含特定字符的范围

二.使用string::npos返回无效位置

三.总结


在C++中, std::string 类的 find 成员函数用于查找子字符串在字符串中的位置。 find 函数有多个重载版本,允许你以不同的方式执行查找操作。

一.find方法基本用法

cpp 复制代码
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World!";
    size_t pos = str.find("World");
    if (pos != std::string::npos) {
        std::cout << "Found 'World' at position: " << pos << std::endl;
    } else {
        std::cout << "The substring 'World' was not found." << std::endl;
    }
    return 0;
}

在这个示例中, find 被用来查找子字符串 "World" 在字符串 str 中的位置。如果找到了, pos 将包含子字符串的起始索引;如果没有找到, pos 将被设置为 std::string::npos 。

1.查找字符

cpp 复制代码
size_t pos = str.find('o');

这个调用查找字符 'o' 在字符串中的位置。

2.查找子字符串

cpp 复制代码
size_t pos = str.find("World");

这个调用查找子字符串 "World" 在字符串中的位置。

3.查找子字符串(从指定位置开始)

cpp 复制代码
size_t pos = str.find("World", 6);

这个调用从索引 6 开始查找子字符串 "World" 。

4.查找字符范围

cpp 复制代码
size_t pos = str.find_first_of("lo");

这个调用查找任何 "lo" 中的字符在字符串中第一次出现的位置。还有 find_last_of 来查找最后一次出现的位置。

5.查找不包含特定字符的范围

cpp 复制代码
size_t pos = str.find_first_not_of("Hdle");

这个调用查找第一个不是 "Hdle" 中的字符的位置。 find_last_not_of 用于查找最后一次出现的位置。

二.使用string::npos返回无效位置

string::npos 是 C++ 标准库中 std::string 类型的一个静态成员常量,表示"未找到"或"无效位置"。当你使用 std::string 的某些方法,如 find 、 rfind 、 find_first_of 等,它们返回一个位置索引时,如果没有找到指定的子字符串或字符,这些方法就会返回 string::npos 。

例如:

cpp 复制代码
std::string str = "Hello, World!";
size_t pos = str.find("test");

if (pos == std::string::npos) {
    // 没有找到子字符串 "test"
}

在这个例子中,如果 str 中没有 "test" 这个子字符串, pos 将被赋值为 string::npos 。

它的值是 std::string 类型能够表示的最大大小加一(通常是 size_t(-1) )。

三.总结

find 函数是 std::string 类中非常有用的成员函数之一,它提供了灵活的方式来查找子字符串或字符。使用 npos 可以检查查找操作是否成功。

相关推荐
努力努力再努力wz33 分钟前
【CUDA入门系列】CUDA编程实战:设备选择、显存管理、Kernel、Stream 与 Event 全流程梳理
开发语言·c++
沫璃染墨1 小时前
《从零入门Linux系统篇(五十八):线程篇·十一——线程安全与死锁详解:从可重入到多锁管理》
linux·服务器·开发语言·c++·驱动开发·安全·架构
郝学胜_神的一滴1 小时前
C++ Templates 05:那些容易踩坑的技巧性基础知识
c++·visual studio
朝朝辞暮i1 小时前
C++ 第 40 章:ROS2 Publisher + Timer + Subscriber + Callback + Executor 完整闭环
开发语言·c++·算法·ros2
旖旎夜光2 小时前
LeetCode 1576: 替换所有的问号(模拟) —— 题解
c++·学习·算法·leetcode·力控
朝朝辞暮i2 小时前
C++ 第 38 课:线程、SingleThreadedExecutor、MultiThreadedExecutor、Callback Group
开发语言·c++·算法·ros2
(Charon)2 小时前
【C++面试】互斥锁与读写锁:使用场景、实现原理与写饥饿问题
c++·算法
by209993 小时前
list 的使用:把节点、位置和操作联系起来的综合叙述(上)
数据结构·c++·笔记·list
welfare9623 小时前
新号别搞:vector
c++
welfare9623 小时前
新号别搞:string
c++