C++ String find()
Last Updated:
C++ String find()
The find()
method searches for a string inside a given string.
Example
#include <iostream>
using namespace std;
int main()
{
string str1 = "wikimass for programmers";
string str2 = "for";
cout << "Position of 'for': ";
cout << str1.find(str2);
return 0;
}
Syntax
Parameter Values
Value | Type | Explanation |
str1 |
Required |
Specifies a string where the search is performed. |
str2 |
Required |
Specifies a string to search for. |
pos |
Optional |
Specifies the initial position from where the string search is to begin.
Default value of starting position is 0.
|
Return Value
Value | Explanation |
---|
Number (index value) |
Returns the index of the first occurrence of sub-string. |
Garbage value |
If the search value is not found. |
More Examples
In the following example, the search starts from the index value 7
Example
#include <iostream>
using namespace std;
int main()
{
string str1 = "wikimass for programmers";
string str2 = "for";
cout << "Position of 'for': ";
cout << str1.find(str2, 7);
return 0;
}
If the search value is not found, then find() method returns garbage value.
Example
#include <iostream>
using namespace std;
int main()
{
string str1 = "wikimass for programmers";
string str2 = "forest";
cout << "Position of 'forest': ";
cout << str1.find(str2);
return 0;
}
Share this Page
Meet the Author