Coding

strstr Function in C: Find a Substring in a String

The strstr function in C searches a null-terminated string for the first occurrence of another string and returns a pointer to where it starts, or NULL if there is no match. It is declared in <string.h>, and you turn the returned pointer into an index by subtracting the start of the searched string.

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "one two three";
    const char *match = strstr(text, "two");

    if (match != NULL) {
        printf("found at index %td\n", match - text);
    } else {
        puts("not found");
    }
    return 0;
}

Example output: found at index 4.

The signature and what strstr returns

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

The Linux man page names the arguments haystack (the string you search in) and needle (the string you look for); cppreference calls them str and substr. Both must point to null-terminated byte strings. The terminating null characters are not compared, so the function never reports a match that includes the terminator.

SituationReturn value
Needle foundpointer to the first character of the first match inside the haystack
Needle not foundNULL
Needle is an empty stringthe haystack pointer itself
Either argument is not a null-terminated stringundefined behavior

The man page also gives an exact equivalence: strstr(haystack, needle) behaves like memmem(haystack, strlen(haystack), needle, strlen(needle)). That helps explain the behavior. The function looks at the haystack only up to its first null byte, and a match has to fit completely before that byte.

How to check whether a string contains a substring

Standard C has no contains function. The idiom is to compare the result of strstr with NULL:

if (strstr(line, "ERROR") != NULL) {
    /* line contains ERROR */
}

A pointer can be used directly as a condition, so if (strstr(line, "ERROR")) also works. Writing the comparison with NULL makes the intent clearer to the next reader. Either way, remember that the result is a pointer and not an index, so a match at the very start of the string is a valid, non-null pointer. That is different from functions that return an index and use 0 for the first position.

How to get the position (index) of the match

Pointer subtraction gives the offset in characters from the start of the haystack. The cppreference example does exactly this and prints the result with %td, the format specifier for ptrdiff_t:

const char *str = "one two three";

const char *pos = strstr(str, "n");
if (pos) {
    printf("index %td\n", pos - str);   // index 1
}

The subtraction is only meaningful when pos is not NULL, so keep it inside the if. Subtracting a null pointer from a valid one is not defined. The index is zero-based, which is why "n" in "one two three" is at index 1.

What strstr does with an empty needle

Searching for an empty string is a common surprise. Both sources document that strstr(text, "") returns text, so the match is reported at index 0 even when the haystack is itself empty. The cppreference example output shows it: searching "one two three" for "" reports a match at position 0.

This matters when the needle comes from user input or a file. If an empty field slips through, a check like strstr(line, filter) != NULL becomes true for every line. Test the needle first when empty input is possible:

if (filter[0] != '\0' && strstr(line, filter) != NULL) {
    /* a real, non-empty match */
}

Find every occurrence, not just the first

strstr returns only the first match. To find the rest, search again starting just after the previous match. Advance by one character if you want overlapping matches, or by the needle length if you do not:

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "abababa";
    const char *needle = "aba";
    size_t needle_length = strlen(needle);

    if (needle_length == 0) {
        return 1;   // an empty needle would loop forever
    }

    const char *cursor = text;
    while ((cursor = strstr(cursor, needle)) != NULL) {
        printf("match at index %td\n", cursor - text);
        cursor += needle_length;   // use cursor += 1 to allow overlaps
    }
    return 0;
}

Example output: match at index 0, then match at index 4. With cursor += 1 the matches are at indexes 0, 2 and 4. The guard on an empty needle is not optional. An empty needle always matches, and advancing by zero characters would repeat the same match forever.

How to replace or extract text with the returned pointer

Once you have the pointer, the rest of the string is available from that point on, because the match is a normal pointer into the original. Printing match with %s prints everything from the match to the end of the string. To copy only the part before the match, use the pointer difference as a length:

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *line = "name=alex";
    const char *separator = strstr(line, "=");

    if (separator != NULL) {
        size_t key_length = (size_t)(separator - line);
        printf("key: %.*s\n", (int)key_length, line);
        printf("value: %s\n", separator + 1);
    }
    return 0;
}

Example output: key: name and value: alex. The %.*s format prints at most the given number of characters, so you do not need a temporary copy. For a single character, strchr is the simpler tool, and cppreference lists it next to strstr as the related function for characters.

Const correctness and the C23 change

Both parameters are const char *, so strstr does not modify the strings you pass. The traditional return type, however, is a plain char *. That means the function can hand you a writable pointer into a string you declared const, and the compiler will not warn you. Writing through such a pointer is undefined behavior when the original is a string literal or another const object.

C23 addresses this. According to cppreference, strstr becomes a type-generic macro: given a const char * it returns const char *, and given a char * it returns char *. Wrapping the name in parentheses, as in (strstr)(a, b), or taking its address gives the older non-generic function. The Linux man page lists C11 and POSIX.1-2008 as the standards for the function and does not mention C23. Which behavior you get therefore depends on your compiler and the language mode you select. Store the result in a const char * unless you really need to write through it.

Case-insensitive search

strstr compares characters exactly, so strstr("Error: disk full", "error") returns NULL. The standard library does not provide a case-insensitive variant. The man page lists strcasestr(3) only under See also, and it is not part of the C standard, so portable code should not rely on it. A portable approach is to copy both strings into buffers, lower-case the copies with tolower from <ctype.h>, cast each character to unsigned char first, and search the copies. If you need the position in the original, it is the same index, as long as you only change the case of single-byte characters.

The same exact-match rule is the reason string equality has its own function. For whole-string comparison, see strcmp in C: how to compare strings correctly.

Common mistakes with strstr

  • Using the result without a NULL check. Passing NULL to printf("%s") or dereferencing it is undefined behavior. Check first.
  • Treating the result as an index. It is a pointer. Subtract the haystack start to get an index.
  • Passing a buffer without a terminator. The function reads until it finds a null byte, so a missing terminator can read past the end of the array. See strings in C: char arrays and the null terminator for how terminators go missing.
  • Forgetting the newline from fgets. A line read with fgets usually ends in \n. If the needle is the user's input and still has that newline, nothing will match. Strip it first, as shown in fgets in C: read a line safely.
  • Looping on an empty needle. An empty needle always matches, so a loop that advances by the needle length never ends.
  • Searching binary data. The search stops at the first zero byte in either argument. Use memmem where it exists, or a loop with memcmp.
  • Writing through the returned pointer of a literal. The return type allows it, but modifying a string literal is undefined behavior.

If strstr does not find what you expect

Print both strings between delimiters, for example printf("[%s] [%s]\n", text, needle);. Trailing spaces, a newline or a carriage return (\r) from a text file will show up inside the brackets. Next, check the case, because the search is exact. Finally, confirm that the haystack really is the string you think it is. A common cause is searching a pointer that was reassigned or a buffer that was overwritten by a later read.

Frequently asked questions

What does strstr return if the substring is not found?
strstr returns a null pointer when the substring does not occur in the string. If the substring is found, it returns a pointer to its first character inside the original string. Always test the result against NULL before you use it, because dereferencing a null pointer is undefined behavior.
What does strstr return for an empty substring?
If the substring is an empty string, strstr returns the first argument, which is a pointer to the start of the searched string. Both cppreference and the Linux man page document this. It means an empty needle always counts as found, at position 0.
How do I get the index of the substring from strstr?
Subtract the start of the string from the returned pointer: index = result - text. The difference has type ptrdiff_t, so print it with the %td format specifier. The subtraction is only valid when the result is not NULL and both pointers point into the same array.
Is strstr case sensitive?
Yes. strstr compares characters exactly, so searching for 'Error' will not match 'error'. Standard C has no case-insensitive version. A portable workaround is to copy both strings, convert the copies to one case with tolower, and search the copies.
Does strstr work on binary data?
Not reliably. strstr stops at the first null byte in both arguments, so it only works on null-terminated byte strings. For data that can contain zero bytes, use memmem where your platform provides it, or write a loop around memcmp.

Sources