The strrchr() function scans a C-string from start to end and returns a pointer to the last occurrence of a given character. Where strchr() finds the first match, strrchr() finds the final one—ideal for file extensions, trailing path separators, and the rightmost delimiter in a line.
01
Last Match
Rightmost char.
02
char* Return
Or nullptr.
03
Index
ptr - str.
04
vs strchr
First vs last.
05
Paths
Slash & dot.
06
<cstring>
C library function.
Fundamentals
Definition and Usage
In C++, strrchr() is declared in <cstring>. It walks the entire null-terminated string and remembers the most recent position where the target character appeared. When the scan finishes, it returns that address or nullptr if the character never occurred.
The second parameter is typed as int but holds a character value such as '/' or '.'. The returned pointer points into the original string—no new memory is allocated.
💡
Beginner Tip
To get a file extension from report.final.pdf, use strrchr(path, '.'). The pointer references the last dot; dot + 1 is the substring pdf.
Foundation
📝 Syntax
Function signature and a typical call:
C++
#include <cstring>
char* strrchr(const char* str, int character);
// Example:
const char* lastO = strrchr("Hello, C++ programming!", 'o');
// index == 13 when lastO is not nullptr
Parameters
str — null-terminated C-string to search.
character — character to find, passed as an int (e.g. 'o').
Return Value
Pointer to the last matching character in str, or nullptr if the character is absent.
Cheat Sheet
⚡ Quick Reference
Function
Finds
Typical use
strchr()
First occurrence
Start of token, first @
strrchr()
Last occurrence
Extension, final /
strpbrk()
First char from set
Any delimiter in set
std::string::rfind
Last substring/char
Modern C++ strings
Search
strrchr(s, ch)
Last match
Found?
p != nullptr
Null check
Index
p - s
Zero-based
Extension
strrchr(s, '.')
Last dot
Hands-On
Examples Gallery
Compile with g++ strrchr.cpp -std=c++17 -o strrchr. Always verify the return pointer is not nullptr before using it.
📚 Getting Started
Locate the rightmost occurrence of a character and print its index.
Example 1 — Find the Last 'o'
Search "Hello, C++ programming!" for the final letter o.
First '/': index 0
Last '/': index 15
Filename: report.pdf
How It Works
strchr finds the leading slash; strrchr finds the slash before the filename. lastSlash + 1 skips past that delimiter.
Example 4 — Parent Directory from a Path
Print everything before the final slash when a path contains folders.
C++
#include <iostream>
#include <cstring>
int main() {
const char* fullPath = "C:/projects/cpp/strrchr.cpp";
const char* slash = std::strrchr(fullPath, '/');
if (slash == nullptr) {
slash = std::strrchr(fullPath, '\\');
}
if (slash != nullptr) {
std::cout << "Directory: ";
for (const char* p = fullPath; p != slash; ++p) {
std::cout << *p;
}
std::cout << "\n";
}
return 0;
}
📤 Output:
Directory: C:/projects/cpp
How It Works
The last separator defines where the directory portion ends. Production code often uses std::filesystem::path, but strrchr shows the underlying C-string technique.
Example 5 — Character Not Found
When the character never appears, the function returns nullptr.
C++
#include <iostream>
#include <cstring>
int main() {
const char* word = "strrchr";
const char* atSign = std::strrchr(word, '@');
if (atSign == nullptr) {
std::cout << "No '@' in \"" << word << "\"\n";
} else {
std::cout << "Found '@' at " << (atSign - word) << "\n";
}
return 0;
}
📤 Output:
No '@' in "strrchr"
How It Works
Never dereference or subtract from a null pointer. Branch on nullptr first, then compute atSign - word.
Applications
🚀 Common Use Cases
File extensions — locate the last dot in a filename.
Path parsing — find the final slash or backslash before the basename.
Trailing delimiters — split on the last comma or semicolon in a line.
Log analysis — find the last colon in a timestamp or level prefix.
Pairing with strchr() — first and last bounds of a substring region.
🧠 How strrchr() Works
1
Scan from start
Walk str from index 0 toward the null terminator.
Scan
2
Compare each byte
If current char equals target, remember this address as the latest match.
Match
3
Continue to end
Do not stop at the first hit—keep updating until '\0'.
Loop
📍
🔍
Return last hit
Final remembered pointer, or nullptr if no character matched.
Important
📝 Notes
The returned pointer aliases memory inside str—valid only while that buffer lives.
The search character is an int; char literals like '/' work directly.
Case-sensitive: 'A' and 'a' are different targets.
Passing '\0' finds the string terminator (advanced edge case).
For std::string, prefer s.rfind('.') instead of strrchr(s.c_str(), '.').
Performance
⚡ Optimization
strrchr() always scans the full string once, even if the last match is near the end. For very long strings searched repeatedly, consider scanning backwards manually or caching parsed path components. Library implementations are typically optimized for common cases.
Wrap Up
Conclusion
strrchr() locates the final occurrence of one character in a C-string. Use it for extensions, trailing separators, and any task where the rightmost match matters. Check for nullptr, then use pointer arithmetic to read index or suffix text.
Next, learn strspn() to count how many initial characters all belong to an accept set—the complement of strcspn().
Use strrchr when any char from a set will do—use strpbrk
Keep pointers after the source string is destroyed
Assume the first dot is the extension dot on multi-dot names
Forget Windows paths may need both / and \\
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strrchr()
Use these points when searching from the right.
5
Core concepts
🔍01
Last Match
Rightmost char.
Basics
🚫02
nullptr
Not found.
Return
🔄03
vs strchr
Last vs first.
Compare
📁04
Extension
Last dot.
Use case
📍05
Index
p - str.
Pattern
❓ Frequently Asked Questions
strrchr() searches a null-terminated C-string for the last (rightmost) occurrence of a character. It returns a pointer to that character inside the string, or nullptr if the character is not found.
char* strrchr(const char* str, int character); Include <cstring>. The second argument is an int holding a character value such as 'o' or '.'.
A pointer to the last matching character in str, or nullptr if no match exists. Compute the index with result - str when result is not nullptr.
strchr() returns the first (leftmost) match. strrchr() returns the last (rightmost) match. Use strchr for the start of a token; use strrchr for file extensions or the final path separator.
Yes. If you pass '\0' as the character, strrchr returns a pointer to the end of the string (the terminating null byte). This is rarely needed but is defined behavior.
Use strrchr() on C-style char* strings and in C API code. Use std::string::rfind() on std::string objects—it returns a size_t index or npos and fits modern C++ more naturally.
Did you know?
The extra r in strrchr stands for reverse search direction in spirit—you still scan forward, but you keep the last match. C++ std::string::rfind follows the same idea for modern strings.