Searching for characters with strchr and strrchr
What you'll learn: How to locate the first or last occurrence of a specific character within a string.
Imagine you are scanning a long bookshelf for a specific book. Your eyes might move from left to right to find the first copy, or you might start from the far right to find the very last one. In C, the strchr and strrchr functions perform this exact task for strings.
The Forward Search: strchr
The function strchr (short for "string character") searches a string from left to right. It looks for the first time a specific character appears.
Instead of returning a simple number (like an index), it returns a pointer to that character’s location in memory. Think of this like a laser pointer hitting the exact spot on the shelf where the book sits. If the character isn't found, the function returns NULL.
The Reverse Search: strrchr
The strrchr function (the extra 'r' stands for "reverse") works identically, but it starts scanning from the end of the string and moves backward. This is incredibly useful when you need the last occurrence of something, such as finding the file extension in a full file path like photos/vacation/beach.jpg. You don't want the first slash; you want the last one.
Seeing it in Action
To use these, include <string.h>. Note that even though you are looking for a char, the functions technically expect an int for the character argument (C handles the conversion for you).
#include <stdio.h>
#include <string.h>
int main() {
char message[] = "Hello, world! Welcome to C.";
// Find the first 'o'
char *first_o = strchr(message, 'o');
// Find the last 'o'
char *last_o = strrchr(message, 'o');
if (first_o != NULL) {
printf("First 'o' found at position: %ld\n", first_o - message);
printf("Last 'o' found at position: %ld\n", last_o - message);
}
return 0;
}
By subtracting the start of the string (message) from the pointer returned by the function, we can calculate the exact index where the character lives.
Key takeaway
Use strchr to find the first occurrence of a character and strrchr to find the last occurrence.