Course contentsShow
← C
Lesson 852 of 1,21912. The Standard LibraryFree lesson

Finding substrings with `strstr`

Finding substrings with strstr

What you'll learn: How to search for a specific sequence of characters within a larger string using the strstr function.

The Needle in the Haystack

Searching for text is one of the most common tasks in programming. Whether you are looking for a specific word in a sentence or checking if a URL contains "https", you are performing a substring search. In C, the strstr function (short for "string string") is your primary tool for this.

Think of it like a metal detector. You have a large field (the haystack) and you are waving your detector to find a specific metal object (the needle). strstr scans the haystack from left to right. If it finds the needle, it stops and points exactly to where that needle begins.

How it Works

To use strstr, you need the <string.h> header. The function takes two arguments: the string you are searching through and the string you are looking for.

One unique aspect of strstr is what it returns. It doesn't give you a "Yes" or "No" or a simple number. Instead, it returns a pointer to the first occurrence of the substring. If the substring isn't found, it returns NULL.

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

int main() {
    char haystack[] = "Learning C is a rewarding journey.";
    char needle[] = "rewarding";
    char *result;

    // Search for "rewarding" inside the haystack
    result = strstr(haystack, needle);

    if (result != NULL) {
        // If found, 'result' points to the start of "rewarding" inside the original string
        printf("Found the substring! Starting at: '%s'\n", result);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

Important Nuances

  1. Case Sensitivity: strstr is picky. It treats "Apple" and "apple" as completely different things.
  2. First Occurrence Only: If your word appears three times, strstr only cares about the first one it hits.
  3. The Pointer Return: Because it returns a pointer to a location inside your original string, you can actually use that pointer to modify the original text or calculate the exact index (position) by subtracting the starting address of the haystack from the result.

Key takeaway

Use strstr(haystack, needle) to locate the first occurrence of a substring; it returns a pointer to the match or NULL if nothing is found.