Open In App

string find in C++

String find is used to find the first occurrence of a sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from the given starting position. The default value of starting position is 0.

It is a member function of std::string class.



Syntax:

size_t find (const string& str, size_t pos = 0); // for C++ Style Strings
         or
size_t find (const char* s, size_t pos = 0);     // for C-Style Strings

Parameters:



Return Value:

Complexity analysis:

Example:




// C++ program to demonstrate
// working of string.find()
#include <iostream>
#include <string>
using namespace std;
 
// Driver code
int main()
{
  string str = "geeksforgeeks a computer science";
  string str1 = "geeks";
   
  // Find first occurrence of "geeks"
  size_t found = str.find(str1);
  if (found != string::npos)
    cout << "First occurrence is " <<
             found << endl;
   
  // Find next occurrence of "geeks".
  // Note here we pass
  // "geeks" as C style string.
  char arr[] = "geeks";
  found = str.find(arr, found+1);
  if (found != string::npos)
    cout << "Next occurrence is " <<
             found << endl;
  return 0;
}

Output
First occurrence is 0
Next occurrence is 8

Find the occurrence of a character

We can use the find function to find the occurrence of a single character too in the string.

 Syntax:

size_t find (const char c, size_t pos = 0);

Here, c is the character to be searched.

Example:




// C++ program to demonstrate
// working of string find
// to find occurrence of
// a character
#include <iostream>
#include <string>
using namespace std;
 
// Driver code
int main()
{
  string str = "geeksforgeeks a computer science";
  char c = 'g';
 
  // Find first occurrence of 'g'
  size_t found = str.find(c);
  if (found != string::npos)
    cout << "First occurrence is " <<
             found << endl;
   
  // Find next occurrence of 'g'
  found = str.find(c, found + 1);
  if (found != string::npos)
    cout << "Next occurrence is " <<
             found << endl;
  return 0;
}

Output
First occurrence is 0
Next occurrence is 8

Search for a partial string

We can also search for a part of the given string.

Syntax:

size_t find (const char *str, size_t pos, size_t n); 

Here, n is the number of characters to match.

Example:




// C++ program to demonstrate
// working of string find to
// search a string
#include <iostream>
#include <string>
using namespace std;
 
// Driver code
int main()
{
  string str = "geeksforgeeks a computer science";
   
  // Only search first 5 characters
  // of "geeks.practice"
  size_t found = str.find("geeks.practice",
                          0, 5);
  if (found != string::npos)
    cout << found << endl;
  return 0;
}

Output
0

Article Tags :
C++