VOOZH about

URL: https://www.geeksforgeeks.org/cpp/string-find-in-cpp/

⇱ String find() in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String find() in C++

Last Updated : 11 Jul, 2025

In C++, string find() is a built-in library function used to find the first occurrence of a substring in the given string. Let’s take a look at a simple example that shows the how to use this function:


Output
8

Explanation: The function returned the starting index of the first occurrence of substring sub in the string s.

Syntax

string find() is a member function of std::string class defined inside <string> header file and have 3 implementations.

The 2nd implementation only works with C style strings.

Parameters

  • s: String which is to be searched.
  • sub: Substring to search. Can be C++ or C style string.
  • pos: Position from where the string search is to begin. By default, it is 0.
  • n: Number of characters to match.

Return Value

  • Returns the integer representing the index of the first occurrence of the sub-string.
  • If the sub-string is not found, it returns string::npos.

To learn how to use the find function effectively, the C++ Course provides practical examples and detailed explanations.

Examples of string find()

The following examples demonstrate the use of string find() function for different purposes.

Check if Substring Exists


Output
hello NOT found.

Explanation: In the above program we checked the string s to find the substring sub using the string find() function. As the string s does not contains any instance of string sub the string find() function returns string::npos.

Find Multiple Occurrences of a Substring


Output
11 19

Explanation: In the above program a loop is used that runs till string find() returns string::npos and in each iteration, the part of the string where the previous occurrence was found is not considered in the search. In this way the program finds all the occurrences of the string sub withing the string s.

Find All the Occurrences of a Character


Output
1 6 

Explanation: The above program uses a loop that runs till string find() returns string::npos and within the loop a string find function is used which finds the occurrences of the character 'c' in the given string , after each iteration,part of the string where the previous occurrence of the character was found is not considered in the search. In this way the program finds all the occurrences of the character c withing the string s.

Find Occurrence of a Partial Substring


Output
3

Explanation: The third parameter in the string find() function is used to specify the first n characters of the substring to be matched. we have matched the first 4 characters of the substring in the above program.

Comment
Article Tags: