C++ String find()
You are Here:
C++ String find()
The find()
method searches for a string inside a given string.
Example
C++ Compiler
#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;
}
Output
Position of 'for': 9
Syntax
str1.find(str2, pos)
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
C++ Compiler
#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;
}
Output
Position of 'for': 9
If the search value is not found, then find() method returns garbage value.
Example
C++ Compiler
#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;
}
Output
Position of 'forest': 18446744073709551615
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on C++ with examples for quick and easy learning.
We are working to cover every Single Concept in C++.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.