strstr() Find the first occurrence of a substring
strstr() Find the first occurrence of a substring
strstr() finds the first case-sensitive match, returning a pointer inside haystack or NULL. An empty needle returns haystack; check the result before use.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
char *strstr(const char *haystack, const char *needle);
⚙️ Parameters
| haystack Required | The string in which to search. |
|---|---|
| needle Required | The substring to locate. |
Returns: Returns a pointer to the start of the match, or NULL if none exists. If needle is empty, returns haystack.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
programming
⚠️ Warning Both arguments must be valid null-terminated strings. The result points inside haystack and must be checked for NULL before use.
💡 Tip Use strchr() for a single character; strstr() is intended for an entire substring.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QWhat does strstr return when needle is an empty string?
AThe standard specifies haystack as the result, meaning the start of the main string, rather than NULL.
QIs strstr case-sensitive when finding a substring?
AYes. Every character in needle must match by byte value, so "World" does not match "world".
QHow can I use strstr to find the second and all subsequent matches?
AAfter finding a match, advance strlen(needle) characters from its start and call strstr at the new position until it returns NULL; this finds non-overlapping matches. For overlapping matches, advance only one character each time. An empty needle returns the original starting point, so handle it separately to avoid an infinite loop.