String Find Function - C++ Programming Tutorial
C++ Course / Strings / String Find Function

String Find Function

BLUF: Mastering String Find Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Find Function

C++ is renowned for its efficiency. Learn how String Find Function enables low-level control and high-performance computing in the tutorial below.

C++ String Find

This function is employed to locate a specified subsequence.

Syntax

Consider two strings labeled as str1 and str2 in the given syntax.

Example

str1.find(str2);

Parameters

str : String to be searched for.

It specifies the character position from where the search should begin.

n : Represents the total count of characters within a specified string that will be targeted for searching.

ch : It defines the character to search for.

Return value

It provides the index of the initial character in the first occurrence.

Example 1

Let's see the simple example.

Example

#include<iostream>
using namespace std;
int main()
{
string str= "java is the best programming language";
cout <<  str<<'\n';
cout <<" Position of the programming word is :";
cout<< str.find("programming");
return 0; 
}

Output:

Output

Java is the best programming language
Position of the programming word is 17

Example 2

Let's examine a basic example by providing the position of a character as an argument.

Example

#include<iostream>
using namespace std;
int main()
{
string str= "Mango is my favorite fruit";
cout <<  str<<'\n';
cout<< " position of fruit is :";
cout<< str.find("fruit",12);
return 0; 
}

Output:

Output

Mango is my favorite fruit
Position of fruit is 21

Example 3

Let's examine a basic example of locating a single character.

Example

#include<iostream>
using  namespace std;
int main()
{
string str = "javacpptutorial";
cout << "String contains :" << str;
cout<< "position of p is :" << str.find('p');
return 0;
}

Output:

Output

String contains : javacpptutorial
         Position of p is 5

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience