C++ String find()

Last Updated:

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; }

Syntax

str1.find(str2, pos)

Parameter Values

ValueTypeExplanation
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

ValueExplanation
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; }

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; }

Share this Page

Meet the Author