C++ String find()

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
str1RequiredSpecifies a string where the search is performed.
str2RequiredSpecifies a string to search for.
posOptionalSpecifies 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 valueIf 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; }

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.

Share this Page

Meet the Author