[温习C/C++]C++刷题技巧—字符串查找find、find_if、find_first_of和find_last_of

系列文章目录

[温习C/C++]0x00-STL标准模板库概述
[温习C/C++]0x01-STL泛型算法-持续更新长文版
[温习C/C++]0x03-sort排序
[温习C/C++]0x04 C++刷题基础编码技巧
[温习C/C++]0x05 C++刷题技巧---set自定义排序及查找
[温习C/C++]0x06 坐标系中矩形重叠类问题分析

C++刷题技巧---字符串查找find、find_if、find_first_of和find_last_of

更新日志

日期 变更内容
2025-10-01 完成初稿

std::find

定义

cpp 复制代码
Defined in header <algorithm>		

template <class InputIterator, class T>   InputIterator find (InputIterator first, InputIterator last, const T& val);

说明

  • 核心功能:在指定范围 [first, last) 内查找与值 val 相等的元素。

  • 返回结果:

    若找到匹配元素,返回指向该首个匹配元素的迭代器;

    若未找到匹配元素,返回指向范围末尾(即 last)的迭代器。

  • 查找范围:左闭右开区间 [first, last) ,意味着包含 first 指向的元素,不包含 last 指向的元素。

例子

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

using namespace std;

int main()
{
    const auto v = {1, 2, 3, 4};
    for (auto& n : {3, 5}) {
        if (find(v.begin(), v.end(), n) == v.end()) {
            cout << "v does not contain " << n << endl;
        } else {
            cout << "v contains " << n << endl;
        }
    }
}
  • 输出
bash 复制代码
v contains 3
v does not contain 5

std::find_if

定义

cpp 复制代码
template <class InputIterator, class UnaryPredicate>   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

说明

  • 核心功能:

    在指定范围 [first, last) 内查找与值 val 相等的元素。

  • 返回结果:

    若找到匹配元素,返回指向该首个匹配元素的迭代器;

    若未找到匹配元素,返回指向范围末尾(即 last)的迭代器。

  • 查找范围:左闭右开区间 [first, last),意味着包含 first 指向的元素,不包含 last 指向的元素。

例子

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

using namespace std;

int main()
{
    auto is_even = [](int i) { return i % 2 == 0; };
    vector<int> nums = {3, 1, 4, 1, 3, 5};
    if (auto it = std::find_if(nums.begin(), nums.end() ,is_even); it != nums.end()) {
        cout << "w contains an even number " << *it << endl;
    } else {
        cout << "w does not contain even numbers" << endl;
    }
}
  • Output
bash 复制代码
w contains an even number 4

std::find_first_of

定义

cpp 复制代码
equality (1)	
template <class InputIterator, class ForwardIterator>   InputIterator find_first_of (InputIterator first1, InputIterator last1, orwardIterator first2, ForwardIterator last2);

predicate (2)	
template <class InputIterator, class ForwardIterator, class BinaryPredicate>   InputIterator find_first_of (InputIterator first1, InputIterator last1,  orwardIterator first2, ForwardIterator last2,  BinaryPredicate pred);

说明

判断是否有前者[first1, last1) 是否有包含后者[first2, lasht2) 的子串。

例子

参考资料: https://cplusplus.com/reference/algorithm/find_first_of/

cpp 复制代码
#include <iostream>     // std::cout
#include <algorithm>    // std::find_first_of
#include <vector>       // std::vector
#include <cctype>       // std::tolower

bool comp_case_insensitive (char c1, char c2) {
    return (std::tolower(c1)==std::tolower(c2));
}

int main () {
    int mychars[] = {'a','b','c','A','B','C'};
    std::vector<char> charStack (mychars,mychars+6);
    std::vector<char>::iterator it;

    int needle[] = {'A','B','C'};

    // using default comparison:
    it = find_first_of (charStack.begin(), charStack.end(), needle, needle + 3);

    if (it!=charStack.end())
        std::cout << "The first match is: " << *it << '\n';

    // using predicate comparison:
    it = find_first_of (charStack.begin(), charStack.end(),
                        needle, needle + 3, comp_case_insensitive);

    if (it!=charStack.end())
        std::cout << "The first match is: " << *it << '\n';

    return 0;
}
  • Output
bash 复制代码
The first match is: A
The first match is: a

std::find_last_of

定义

cpp 复制代码
size_type find_last_of( const basic_string& str,
                        size_type pos = npos ) const;
                        
size_type find_last_of( CharT ch, size_type pos = npos ) const;

说明

查找与给定字符序列中的某个字符相等的最后一个字符。具体的搜索算法未指定。搜索仅考虑范围[0, pos]。如果在该范围内不存在给定字符序列中的任何字符,则返回npos。

例子

cpp 复制代码
#include <iostream>
#include <string>
 
int main()
{
    const std::string path = "/root/config";
    auto const pos = path.find_last_of('/');  // pos = 5
    const auto leaf = path.substr(pos + 1);   // pos + 1 = 6
 
    std::cout << leaf << '\n';
}
  • Output
bash 复制代码
config

Leetcode 345.反转字符串中的元音字母

给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。

元音字母包括 'a'、'e'、'i'、'o'、'u',且可能以大小写两种形式出现不止一次。

示例 1:

输入:s = "IceCreAm"

输出:"AceCreIm"

解释:

s 中的元音是 ['I', 'e', 'e', 'A']。反转这些元音,s 变为 "AceCreIm".

示例 2:

输入:s = "leetcode"

输出:"leotcede"

提示:

1 <= s.length <= 3 * 105

s 由 可打印的 ASCII 字符组成


cpp 复制代码
class Solution {
public:
    string reverseVowels(string s) {
        int left=0,right=s.size()-1;
        while(left<right)
        {
            left=s.find_first_of("aeiouAEIOU",left);
            right=s.find_last_of("aeiouAEIOU",right);
            if(left<right)
            {
                swap(s[left++],s[right--]);
            }
        }
        return s;
    }
};

输入:s = "IceCreAm"

输出:"AceCreIm"

相关推荐
初圣魔门首席弟子3 小时前
c++嵌套类和局部类详细介绍
java·开发语言·c++
橘子师兄3 小时前
类和对象(上)
开发语言·c++
Juan_20123 小时前
P1447题解
c++·数学·算法·题解
祁同伟.3 小时前
【C++】栈、队列、双端队列、优先级队列、仿函数
c++·容器·stl
charlie1145141914 小时前
精读C++20设计模式——结构型设计模式:享元模式
c++·笔记·学习·设计模式·享元模式·c++20
NiKo_W5 小时前
C++ 反向迭代器模拟实现
开发语言·数据结构·c++·stl
YA10JUN5 小时前
C++版搜索与图论算法
c++·算法·图论
劲镝丶5 小时前
顺序队列与环形队列的基本概述及应用
数据结构·c++
奔跑吧邓邓子6 小时前
【C++实战(53)】C++11线程库:开启多线程编程新世界
c++·实战·多线程·c++11·线程库