Searching for characters with strchr
What you'll learn: How to locate the first occurrence of a specific character within a string using the strchr function.
The Digital Metal Detector
Imagine you have a long train of boxcars (a string), and you are looking for a specific passenger holding a red flag. You start at the very first car and walk toward the end. The moment you find that passenger, you stop and note exactly where they are standing.
In C, the strchr function acts as your metal detector. It scans a string from left to right until it finds the character you asked for. Instead of telling you the "index number" (like 0 or 5), it returns a pointer to that specific spot in memory.
Using strchr
To use this tool, you need to include <string.h>. The function requires two pieces of information:
- The string you want to search.
- The character you are looking for.
If the character is found, strchr returns a pointer to the first match. If the character isn't there at all, it returns NULL (a special way of saying "not found").
#include <stdio.h>
#include <string.h>
int main() {
char message[] = "Hello, World!";
char target = 'W';
// Search for 'W' in the message
char *result = strchr(message, target);
if (result != NULL) {
// We found it! We can print the string starting from that spot.
printf("Found '%c' at position: %ld\n", target, result - message);
printf("The rest of the string is: %s\n", result);
} else {
printf("Character not found.\n");
}
return 0;
}
Why pointers matter here
Because strchr gives you the memory address of the character, you aren't just getting a "yes" or "no" answer. You are getting a "handle" on the rest of the string starting from that point. In the example above, pointing to the 'W' in "Hello, World!" allows you to easily treat "World!" as its own sub-segment.
Remember: strchr is case-sensitive and only finds the first occurrence. If there are three 'o's in your sentence, it will stop and return the location of the very first one it hits.
Key takeaway
Use strchr to find the memory address of the first occurrence of a character, returning NULL if the character doesn't exist.