A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strchr scans a string from the beginning and returns a pointer to the first occurrence of a given character. If the character is not found, it returns NULL. If you search for the null terminator, it returns a pointer to the end of the string. This is the simplest search function in the C string library, and it is the foundation for strrchr, strpbrk, and countless manual parsing loops.
#include <stdio.h>#include <string.h>int main(void) {const char *email = "user@example.com";char *at = strchr(email, '@');if (at) {printf("@ found at index %ld\n", at - email);printf("Domain: %s\n", at + 1);}char *z = strchr(email, 'z');printf("Search for 'z': %s\n", z ? "found" : "NULL");char *end = strchr(email, '\0');printf("End of string at index: %ld\n", end - email);return 0;}
Searching for '\0' is a valid operation. It returns a pointer to the null terminator, which is equivalent to email + strlen(email). This is occasionally useful when you need a pointer to the end of a string for appending or boundary calculations.
strchr is the atomic unit of string searching. Everything more complex is built on top of it. Next: strspn, the complement of strcspn, which measures how many characters from the start match a given set.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.