【C++】C++中find_first_of函数解析

目录

一.函数介绍

二.函数原型

三.函数示例


一.函数介绍

在C++中, find_first_of  是  std::string  类的一个成员函数,用于在字符串中查找第一次出现的任何字符(或字符序列)的索引位置。这个函数可以接收单个字符或字符序列作为参数,并返回第一个匹配项的起始位置。

二.函数原型

以下是  find_first_of  的一些基本用法:

size_t find_first_of(charT ch, size_t pos = 0) const;
size_t find_first_of(const charT* s, size_t pos = 0) const;
size_t find_first_of(const string& str, size_t pos = 0) const;
size_t find_first_of(const charT* s, size_t pos, size_t n) const;

参数说明

 ch :要查找的单个字符。

 s :要查找的字符序列。

 pos :开始查找的位置(默认为0)。

 str :要查找的字符串。

 n :字符序列的长度。

返回值

返回第一次出现的字符或字符序列的起始位置的索引。如果没有找到,则返回  string::npos 。

示例代码

#include <iostream>
#include <string>


int main() {
    std::string str = "Hello World!";
    std::string chars = "Wo";

    size_t pos = str.find_first_of(chars);
    if (pos != std::string::npos) {
        std::cout << "First occurrence of any character in '" << chars << "' is at position: " << pos << std::endl;
    } else {
        std::cout << "No occurrence of any character in '" << chars << "' found." << std::endl;
    }

    return 0;
}

输出

First occurrence of any character in 'Wo' is at position: 7

在这个例子中, find_first_of  查找字符串  "Hello World!"  中第一次出现的字符  "W"  或  "o"  的位置。结果是  "W"  在位置7首次出现。

三.函数示例

std::string str = "Hello World!";
std::string chars = "abc";

size_t pos = str.find_first_of(chars, 5);  // 从位置5开始查找
if (pos != std::string::npos) {
    std::cout << "First occurrence of any character in '" << chars << "' starting from position 5 is at position: " << pos << std::endl;
} else {
    std::cout << "No occurrence of any character in '" << chars << "' found starting from position 5." << std::endl;
}

在这个例子中,查找从位置5开始,因此不会考虑  "Hello"  中的  "a" 。

 find_first_of  是处理字符串查找任务时非常有用的函数之一。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员赵大宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值