Skip to content
Tutorials Center
My learning

Topics

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.

C
#include <string.h>

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

Try it

C Searching and replacing

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.

C Finding every match

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

C
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 NULL before using the result, as with strchr.
  • 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 at p + strlen(needle) to skip over the match.
  • Const-correctness: as with strchr, the traditional signature returns a non-const char * even for a const haystack. In C23 the return type follows the argument's qualification where the generic form is available. Use a const 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 memmove to shift the tail when the replacement has a different size.
  • Single character? strchr is simpler and faster.