RFIND()
This member of the std::string class searches for the last occurrence of a substring or character within a string. Unlike find(), which searches left-to-right, rfind() searches right-to-left, starting from a given position (defaulting to the end of the string). It returns the index of the first character of the last match found, or the constant std::string::npos if no match exists. This function is useful when you need to locate the most recent occurrence of a substring such as finding the last directory separator in a file path or the last period in a domain name.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "banana";
// find the first occurrence of "na"
size_t first = text.find("na"); // index 2 - left-to-right search
// find the last occurrence of "na"
size_t last = text.rfind("na"); // index 4 - right-to-left search
cout << "First: " << first << endl;
cout << "Last: " << last << endl;
return 0;
}
Last updated