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.

Categorystring.h strings
KindLibrary function
Header<string.h>
C standardC89 / C90

📝 Syntax

char *strstr(const char *haystack, const char *needle);

⚙️ Parameters

haystack RequiredThe string in which to search.
needle RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏