A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strrchr searches from the end of the string backward, returning a pointer to the last occurrence of a given character. The 'r' stands for reverse. Where strchr gives you the first dot in "file.tar.gz", strrchr gives you the last one. This is how you extract file extensions, find the last path separator, or locate the final delimiter in a compound identifier.
#include <stdio.h>#include <string.h>int main(void) {const char *filename = "archive.backup.tar.gz";char *last_dot = strrchr(filename, '.');if (last_dot) {printf("Extension: %s\n", last_dot + 1);}const char *path = "/home/alex/projects/main.c";char *last_slash = strrchr(path, '/');if (last_slash) {printf("Basename: %s\n", last_slash + 1);}char *missing = strrchr(filename, 'z');printf("Search for 'z': %s\n", missing ? "found" : "NULL");return 0;}
last_dot + 1 skips past the dot to the extension text. last_slash + 1 skips past the separator to the filename. The +1 arithmetic is safe because we checked for NULL first. If strrchr returns NULL, adding 1 would give a near-NULL pointer, and dereferencing it would segfault. Always guard.
#include <stdio.h>#include <string.h>int main(void) {const char *s = ".hidden";char *dot = strrchr(s, '.');if (dot) {printf("Found at index: %ld\n", dot - s);printf("After dot: \"%s\"\n", dot + 1);}const char *s2 = "noext";char *dot2 = strrchr(s2, '.');printf("No dot result: %s\n", dot2 ? dot2 : "NULL");return 0;}
For ".hidden", the dot is at index 0. strrchr finds it. dot + 1 points to "hidden". This is a Unix hidden file, not a file with an extension. Your code needs to decide whether a leading dot counts as an extension separator. strrchr does not make that judgment for you. It just finds the character.
strrchr is a small function with outsized utility in file handling, URL parsing, and identifier splitting. Next: strstr, which searches for an entire substring rather than a single character.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.