C++ String rfind() Function
Example
Find the first and the last position of "apples" in a string:
string txt = "I love apples, and apples love me.";
cout << txt.find("apples") << "\n";
cout << txt.rfind("apples");
Definition and Usage
The rfind() function searches a string for a value, starting from the end. It returns the position of the last match.
The find() function does the same, but it returns the position of the first match. The first character of a string has position 0.
The rfind function is defined in the <string> header file.
Tip: If the value is not found, rfind() returns string::npos. You can check for it, like if (txt.rfind("pears") == string::npos).
Syntax
string.rfind(value);
string.rfind(value, start);
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The string or character to search for. |
| start | Optional. The position to start searching backwards from. Only matches that begin at or before this position are found. Default is the end of the string. |
Technical Details
| Returns: | The position of the first character of the last 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.