C++ String strrchr() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Reverse search

What You’ll Learn

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.

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.

📝 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.

⚡ Quick Reference

FunctionFindsTypical use
strchr()First occurrenceStart of token, first @
strrchr()Last occurrenceExtension, final /
strpbrk()First char from setAny delimiter in set
std::string::rfindLast substring/charModern C++ strings
Search
strrchr(s, ch)

Last match

Found?
p != nullptr

Null check

Index
p - s

Zero-based

Extension
strrchr(s, '.')

Last dot

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.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* sentence = "Hello, C++ programming!";

    const char* lastO = std::strrchr(sentence, 'o');

    if (lastO != nullptr) {
        std::cout << "Last 'o' at index: " << (lastO - sentence) << "\n";
        std::cout << "Character:       " << *lastO << "\n";
    } else {
        std::cout << "'o' not found.\n";
    }

    return 0;
}

How It Works

The first o is in Hello, but strrchr continues scanning and returns the o in programming at index 13.

Example 2 — Extract a File Extension

Use the last dot to separate base name from extension.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* filename = "tutorial.final.cpp";

    const char* dot = std::strrchr(filename, '.');

    if (dot != nullptr) {
        std::cout << "Base:      ";
        for (const char* p = filename; p != dot; ++p) {
            std::cout << *p;
        }
        std::cout << "\nExtension: " << (dot + 1) << "\n";
    }

    return 0;
}

How It Works

The last dot separates tutorial.final from cpp. Using the first dot with strchr would incorrectly split at tutorial.

📈 Practical Patterns

Compare with strchr, parse paths, and handle missing characters.

Example 3 — strrchr() vs strchr()

Same string, same character—different positions returned.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* path = "/home/user/docs/report.pdf";

    const char* firstSlash = std::strchr(path, '/');
    const char* lastSlash  = std::strrchr(path, '/');

    std::cout << "First '/':  index " << (firstSlash - path) << "\n";
    std::cout << "Last '/':   index " << (lastSlash - path) << "\n";
    std::cout << "Filename:   " << (lastSlash + 1) << "\n";

    return 0;
}

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;
}

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;
}

How It Works

Never dereference or subtract from a null pointer. Branch on nullptr first, then compute atSign - word.

🚀 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.

📝 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(), '.').

⚡ 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.

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().

💡 Best Practices

✅ Do

  • Test if (p != nullptr) before dereferencing
  • Use p - str for zero-based index
  • Pick strrchr for last dot or slash in paths
  • Pick strchr when the first match is what you need
  • Include <cstring> and use std::strrchr

❌ Don’t

  • Dereference a null return from strrchr
  • 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 \\

Key Takeaways

Knowledge Unlocked

Five things to remember about strrchr()

Use these points when searching from the right.

5
Core concepts
🚫 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.

Continue the String Functions Series

Search from the end with strrchr(), then scan accept sets with strspn().

Next: strspn() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful