How to use the find_first_of() function in C++

The find_first_of() function is available in the <algorithm> library in C++. This function is used to find the location of the first occurrence of any of the specified characters in a string.

Syntax

The following is the function prototype.

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

Parameters

The find_first_of() method takes the following parameters:

  • String or Character (str): The string or character containing the characters to be searched.

  • Position (pos): This specifies the starting position for the search. By default, this is set to 0.

Return value

The function returns the position of the first occurrence of the character(s) in the specified string/character. If no matches are found, the function returns string::npos.

You can read more about string::npos here.

Code

Let’s have a look at the code.

#include<iostream>
using namespace std;
int main()
{
string s1 = "I got first position and she stood below the first position";
string s2 = "Programming";
cout << "Original string:" << s1<< endl;
// returns 4 as 't' from 'first' is identified at the 4th index (got)
cout << "Position of the first occurrence of the string 'first' is " << s1.find_first_of("first", 1) << endl;
cout << "Original string:" << s2 << endl;
// returns 3 as 'g' from 'Programming' is identified at the 3rd index
cout << "Position of the first occurrence of the character 'g' is " << s2.find_first_of('g', 2);
return 0;
}

Explanation

  • In line 1, we import the required header files.

  • In line 3, we make a main() function.

  • In lines 6 and 7, we initialize two variables of string type.

  • In line 8, we display the first original string.

  • In line 9, we use the find_first_of() function to get the position of the first occurrence of the specified string and the starting position for search and display it with a message.

  • In line 10, we display the second original string.

  • In line 11, we use the find_first_of() function to get the position of the first occurrence of the specified character in the string and the starting position for search and display it with a message.

In this way, we can use the find_first_of() to find the position of the first occurrence of the character of a specified string or character.

Free Resources