C Reference ยท string.h
C strstr() function
Reference for C strstr(): locate the first occurrence of one string inside another, convert the pointer to an index, loop over all matches and avoid mistakes.
strstr() searches a string (the haystack) for the first occurrence of another string (the needle) and returns a pointer to where it starts, or NULL if there is no match. The comparison is case-sensitive and the terminators are not part of the match.
The result points into the haystack. To get the position, subtract the haystack pointer from it.
#include <string.h> char *strstr(const char *haystack, const char *needle);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
char *strstr(const char *haystack, const char *needle);
| Name | Description |
|---|---|
haystack |
The string to search in. |
needle |
The string to look for. |
Returns: a pointer to the first matching position in haystack, or NULL. If needle is empty, the result is haystack itself.
Errors / undefined behavior: both arguments must be terminated strings. NULL is undefined.
Usage notes
- Check for
NULLbefore using the result, as withstrchr. - Case-sensitive. There is no standard case-insensitive version.
strcasestr()is a GNU/BSD extension; portable code lowercases copies of both strings first. - Complexity. Implementations choose their own algorithm. A good library (including glibc) is close to linear in practice, but the standard promises nothing. For huge texts or many searches, consider a dedicated algorithm.
- Overlapping matches. After a hit, restart one character later (
p + 1) to see overlapping occurrences, or atp + strlen(needle)to skip over the match. - Const-correctness: as with
strchr, the traditional signature returns a non-constchar *even for a const haystack. In C23 the return type follows the argument's qualification where the generic form is available. Use aconst char *variable when the haystack is const. - Not for binary data. Embedded zeros stop the search. POSIX
memmem()(a GNU extension, not ISO C) searches raw memory. - Replacing text needs a buffer big enough for the new length. Use
memmoveto shift the tail when the replacement has a different size. - Single character?
strchris simpler and faster.
Related
strchrandstrrchr,strpbrk,strncmp,memchr- Lessons: String functions, Strings