C++ String::find() function



The C++ std::string::find() function is used to detect the position of substring within the string. This function returns the index of the first occurrence of the specified substring or character. If the substring is not found, it returns the string::npos, a constant representing an invalid position.

This function has several overloads, allowing for flexible searches with or without specifying the starting position.

Syntax

Following is the syntax for std::string::find() function.

size_t find (const string& str, size_t pos = 0) const;
or	
size_t find (const char* s, size_t pos = 0) const;
or
size_t find (const char* s, size_t pos, size_t n) const;
or	
size_t find (char c, size_t pos = 0) const;

Parameters

  • str − It indicates the another string object.
  • s − It indicates the pointer to an array of characters.
  • pos − It indicates the position of the first character in the string.
  • n − It indicates the length of sequence of characters to match
  • c − It indicates the individual character to be searched for.

Return value

This function returns the position of the first charcter of first match.

Example 1

In the below program, we have initialized string x = "Tutorialspoint is a educate company!" and given the position to search = "educate" using string::find() function. So it prints position of that particular first character of that word.

#include<iostream>
#include<string>
using namespace std;
int main() {
   string x = "Tutorialspoint is a educate company ";
   cout << x << '\n';
   cout << " educate Position = ";
   cout << x.find("educate");
   return 0;
}

Output

If we run the above code it will generate the following output.

Tutorialspoint is a educate company
educate Position = 20

Example 2

In the below program we have initialized string x = I am a employee in Tutorialspoint. Here, we are passing the position as the parameter by giving x.find(employee, 5). So the output will be printed by using string::find() function.

#include<iostream>
#include<string>
using namespace std;
int main() {
   string x = " I am a employee in Tutorialspoint ";
   cout << x << endl;
   cout << " position of employee = ";
   cout << x.find(" employee", 5);
   return 0;
}

Output

Following is the output of the above code.

I am a employee in Tutorialspoint
position of employee = 7                             

Example 3

Following is the program where we have initialized string x = Tutorialspoint Company!. So here we are finding single chararacter in the string by using string::find() function.

#include<iostream>
#include<string>
using namespace std;
int main() {
   string x = " Tutorialspoint Company ";
   cout << "String = " << x << endl;
   cout << "position = " << x.find('C');
   return 0;
}  

Output

Following is the output of the above code.

String = Tutorialspoint Company
position = 15          
string.htm
Advertisements