strrchr() is a standard C function that returns a pointer to the last occurrence of a character in a null-terminated string. If the character is not found, it returns NULL.
char *strrchr(const char *str, int ch);
#include <stdio.h>
#include <string.h>
int main(void) {
const char text[] = "Welcome to plus2net";
const char *pos = strrchr(text, 'e');
if (pos != NULL) {
printf("Zero-based index: %td\n", pos - text);
printf("From match: %s\n", pos);
} else {
printf("Character not found.\n");
}
return 0;
}
Output
Zero-based index: 17\nFrom match: et
Subtracting the start pointer from the returned pointer gives a zero-based index. Always check for NULL before subtracting or dereferencing the result.
#include <stdio.h>
#include <string.h>
int main(void) {
const char path[] = "docs/c/strings/lesson.txt";
const char *slash = strrchr(path, '/');
const char *filename = (slash != NULL) ? slash + 1 : path;
printf("File name: %s\n", filename);
return 0;
}
Output
File name: lesson.txt
#include <stdio.h>
#include <string.h>
int main(void) {
char text[100];
char ch;
printf("Enter a string: ");
if (fgets(text, sizeof text, stdin) == NULL) {
return 1;
}
text[strcspn(text, "\n")] = '\0';
printf("Enter a character: ");
if (scanf(" %c", &ch) != 1) {
return 1;
}
char *pos = strrchr(text, ch);
if (pos != NULL) {
printf("Last occurrence at index %td.\n", pos - text);
} else {
printf("Character not found.\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char path[] = "file/path/filename.txt";
char *slash = strrchr(path, '/');
if (slash != NULL) {
slash[1] = '\\0';
printf("Directory path: %s\n", path);
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char remaining[] = "plus2net is a great site for tutorials";
const char target = 't';
int count = 0;
char *match;
while ((match = strrchr(remaining, target)) != NULL) {
count++;
*match = '\\0';
}
printf("Occurrences of '%c': %d\n", target, count);
return 0;
}
This mirrors the original backward-search technique. It intentionally works on a mutable copy because each found character is replaced by the null terminator before the next strrchr() call.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.