std::find_first_of() with examples in C++

In this article, we are going to see how to search a character in a string using STL function find_first_of()?
Submitted by Radib Kar, on July 17, 2020

std::find_first_of() as a STL function

find_first_of() in a useful STL function, which is  invoked by a string and searches the first position of any character out of the character list provided(string str) in the argument.

Syntax:

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

Where,

  • const string& str - collection of characters any of which needs to be searched.
  • size_t pos - an optional parameter which is passed with a default value of 0. Position defines the start index of the invoking string from where searching should start.

Return type: size_t

It returns the index if it finds any character of the mentioned collection in the invoking string. If none of the characters is present in the invoking string then it returns a string::npos.

It returns the index immediately if any of the characters found.

Example 1: Position argument not passed, so by default it's 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;
}

Output:

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

Example 2: Position argument is passed

#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;
}

Output:

the second vowel appearing in the string: includehelp is u

In the above case, the starting position is 1 thus it starts searching only from index 1 skipping the first index(0) which is 'i'. Thus, the first character out of the collection which is found is 'u'.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.