In C++, strrchr() searches a C-string for one character and returns the last match. Use it for the final '/' in a path, or the last '.' before a file extension.
Both arguments are required. A match is a pointer into the same string. If the character is missing, the result is nullptr. strchr() stops at the first match. strrchr() keeps the last one. Include <cstring>.
Syntax
Use this when you want the final match, such as the last slash in a path.
C++
strrchr("a/b/c.txt", '/');
Call
What it does
strrchr("a/b/c.txt", '/')
Points at the last / in the path.
Library declarations
C++
const char* strrchr(const char* str, int ch);
Parameters
Parameter
Description
str
Required. The C-string to search.
ch
Required. The character to find, written in single quotes.
Return Value
Return Value
Description
Pointer
Points at the last matching character inside the same string.
nullptr
The character is not in the string.
C++ Examples
Example 1 — Basic strrchr()
Find the last letter in a word.
C++
#include <iostream>
#include <cstring>
int main() {
const char* word = "programming";
const char* found = std::strrchr(word, 'g');
if (found != nullptr) {
std::size_t index = static_cast<std::size_t>(found - word);
std::cout << "Last 'g' at index: " << index << '\n';
std::cout << "From there: " << found << '\n';
}
return 0;
}