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.
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.
#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:
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.
#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:
Mango is my favorite fruit
Position of fruit is 21
Example 3
Let's examine a basic example of locating a single character.
#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:
String contains : javacpptutorial
Position of p is 5