自学内容网 自学内容网

【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  是处理字符串查找任务时非常有用的函数之一。


原文地址:https://blog.csdn.net/qq_35902025/article/details/140544357

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!