In C, strrchr() searches a C-string for the last matching character. It is useful for the last '/' in a path or the last '.' before an extension.
You pass the string and the character. Both are required. The result is a pointer into the same string, or NULL when the character is missing. Include <string.h>.
Syntax
Pass the string and the character. Start with this call.
C
strrchr(path, '/');
Call
What it does
strrchr(path, '/')
Looks for the last '/' in path.
Include <string.h>. Check for NULL. strchr() stops at the first match.
Library declarations
C
char *strrchr(const char *str, int c);
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 to the last match inside the same string.
NULL
Returned when the character is not found.
C Examples
Example 1 — Find the Last Match
Search for the last 'a' and print from that position. Earlier matches are ignored.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *str = "banana";
char *p = strrchr(str, 'a');
if (p != NULL) {
printf("last 'a' at index %td\n", p - str);
printf("suffix: %s\n", p);
} else {
printf("not found\n");
}
return 0;
}
Output
last 'a' at index 5
suffix: a
How It Works
Scan the whole string. Every 'a' updates the remembered match.
Last one wins. In "banana", that is index 5.
Check NULL first. Only then subtract pointers or print.
Contrast with strchr.strchr would stop at index 1.
Example 2 — Get the Filename from a Path
Find the last slash, then print the basename that follows it.