This post will discuss how to find the index of the last occurrence of a char in a C++ string.

1. Using string::rfind

The standard approach to find the index of the last occurrence of a char in a string is using the string::rfind member function. If the character doesn’t occur in the string, the function returns string::npos.

Download  Run Code

2. Using std::find

Alternatively, we can use the std::find algorithm with a reverse iterator and then use the std::distance (or pointer arithmetic) to get the index of the last occurrence.

Download  Run Code

3. Using Loop

Finally, we can iterate over the string in reverse order and find the index of the first matching character. This can be done using a regular for-loop, as shown below:

Download  Run Code

That’s all about finding the index of the last occurrence of a char in a C++ string.