C++ string find() Function
Example
Find the position of "World" and the first 'o' in a string:
string txt = "Hello World!";
cout << txt.find("World") << "\n";
cout << txt.find('o');
Definition and Usage
The find() function searches a string for a value, and returns the position of the first match. The first character of a string has position 0.
The rfind() function does the same, but it returns the position of the last match.
The find function is defined in the <string> header file.
Tip: If the value is not found, find() returns string::npos. You can check for it, like if (txt.find("pears") == string::npos).
Syntax
string.find(value);
string.find(value, start);
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The string or character to search for. |
| start | Optional. The position to start searching from. Default is 0. |
Technical Details
| Returns: | The position of the first character of the first match, as a size_t (a non-negative integer). If nothing is found, it returns string::npos. |
|---|
Related Pages
Read more about strings in our String Tutorial.