当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::find_first_of()用法及代码示例


std::find_first_of() 作为 STL 函数

find_first_of() 在一个有用的 STL 函数中,它由字符串调用,并从参数中提供的字符列表(字符串 str)中搜索任何字符的第一个位置。

用法:

size_t find_first_of (const string& str, size_t pos = 0) const;

其中,

  • const string& str- 需要搜索的任何字符的集合。
  • size_t pos- 一个可选参数,默认值为 0。Position 定义调用字符串的起始索引,从哪里开始搜索。

返回类型: size_t

如果在调用字符串中找到提到的集合的任何字符,则返回索引。如果调用字符串中不存在任何字符,则它返回一个字符串::npos。

如果找到任何字符,它会立即返回索引。

范例1:未传递位置参数,因此默认为 0

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "includehelp";

    string re = "aeiou";
    //its searching in the string str
    //it searches any character from the string re
    //now if any character of re is found then it simply 
    //returns the position of the character found

    cout << "the first vowel appearing in the string:" << str << " is " << str[str.find_first_of(re)] << endl;

    return 0;
}

输出:

the first vowel appearing in the string:includehelp is i
In the above program, 
In the first case,
The invoking string is str, "includehelp"
The collection of characters which are being searched 
"aeiou" -> 'a', 'e', 'i', 'o', 'u'

The position argument is not passed so 
it will start searching from position 0 which is 'i', 
since 'i' falls in the collection of characters thus it returns 0

范例2:位置参数被传递

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "includehelp";

    string re = "aeiou";
    //its searching in the string str
    //it searches any character from the string re
    //now if any character of re is found then it simply 
    //returns the position of the character found

    //now this will start searching in str from position=1
    //thus it skips the fisrt vowel 'i'
    cout << "the second vowel appearing in the string:" << str << " is " << str[str.find_first_of(re, 1)] << endl;

    return 0;
}

输出:

the second vowel appearing in the string:includehelp is u

在上述情况下,起始位置为 1,因此它仅从索引 1 开始搜索,跳过第一个索引 (0),即 'i'。因此,找到的集合中的第一个字符是 'u'。



相关用法


注:本文由纯净天空筛选整理自 std::find_first_of() with examples in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。