A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strstr searches for the first occurrence of a substring within a larger string. It returns a pointer to the beginning of the match, or NULL if the substring does not appear. This is the C standard library's answer to "does this string contain that string?" It is case-sensitive. It does not allocate memory. It does not modify the input. It just scans and returns a pointer.
#include <stdio.h>#include <string.h>int main(void) {const char *haystack = "Error: connection timeout on port 8080";const char *needle = "timeout";char *found = strstr(haystack, needle);if (found) {printf("Found \"%s\" at index %ld\n", needle, found - haystack);printf("Context: \"%s\"\n", found);} else {printf("Substring not found.\n");}char *missing = strstr(haystack, "refused");printf("Search for \"refused\": %s\n", missing ? "found" : "NULL");return 0;}
#include <stdio.h>#include <string.h>int count_occurrences(const char *haystack, const char *needle) {if (*needle == '\0') return 0;int count = 0;const char *pos = haystack;while ((pos = strstr(pos, needle)) != NULL) {count++;pos += strlen(needle);}return count;}int main(void) {const char *text = "the cat sat on the mat with the hat";printf("Occurrences of \"the\": %d\n", count_occurrences(text, "the"));printf("Occurrences of \"at\": %d\n", count_occurrences(text, "at"));return 0;}
The loop advances past each match by the needle's length. This counts non-overlapping occurrences. If you need overlapping matches (finding "aa" in "aaa" should return 2), advance by 1 instead of strlen(needle). The empty-needle guard at the top prevents an infinite loop: strstr with an empty needle returns the haystack itself, and advancing by 0 never terminates.
strstr is the workhorse of substring search in C. Log parsers, protocol handlers, and config file readers use it constantly. For case-insensitive search, POSIX provides strcasestr. The C standard does not. Next: strtok, the controversial string tokenizer that modifies its input and maintains hidden state.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.