0
0
CHow-ToBeginner · 3 min read

How to Use strstr in C: Syntax, Example, and Tips

In C, strstr is used to find the first occurrence of a substring inside another string. It returns a pointer to the start of the substring if found, or NULL if not found. You include <string.h> to use strstr.
📐

Syntax

The strstr function searches for the first occurrence of the substring needle in the string haystack. It returns a pointer to the beginning of the found substring or NULL if the substring is not found.

  • haystack: The main string to search in.
  • needle: The substring to find.
c
char *strstr(const char *haystack, const char *needle);
💻

Example

This example shows how to find the substring "world" inside the string "Hello world!" using strstr. It prints the substring starting from the found position.

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

int main() {
    const char *text = "Hello world!";
    const char *search = "world";

    const char *result = strstr(text, search);

    if (result != NULL) {
        printf("Found substring: %s\n", result);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}
Output
Found substring: world!
⚠️

Common Pitfalls

Common mistakes when using strstr include:

  • Not checking if the return value is NULL before using it, which can cause crashes.
  • Confusing the returned pointer with an index; it returns a pointer, not an integer position.
  • Using strstr with empty strings; searching for an empty substring returns the original string.
c
#include <stdio.h>
#include <string.h>

int main() {
    const char *text = "example";
    const char *search = "z";

    // Wrong: Not checking for NULL
    const char *result = strstr(text, search);
    // printf("Found at: %s\n", result); // This would crash if result is NULL

    // Right: Check before using
    if (result != NULL) {
        printf("Found substring: %s\n", result);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}
Output
Substring not found.
📊

Quick Reference

Remember these points when using strstr:

  • Include <string.h> to use strstr.
  • Returns pointer to substring start or NULL if not found.
  • Check for NULL before using the result.
  • Searching for an empty string returns the original string.

Key Takeaways

Use strstr to find the first occurrence of a substring in a string.
Always check if strstr returns NULL before using the result.
The function returns a pointer to the substring, not an index number.
Searching for an empty substring returns the original string pointer.
Include <string.h> to use strstr.