Course contentsShow
← C
Lesson 428 of 1,2196. Arrays and StringsFree lesson

Searching for substrings with `strstr`

Searching for substrings with strstr

What you'll learn: How to find the first occurrence of a specific phrase within a larger body of text using the strstr function.

The Needle in the Haystack

In C, searching for text is like looking for a specific book on a library shelf. You have a "haystack" (the long string you are searching through) and a "needle" (the short string you want to find).

To do this, we use the strstr function from the <string.h> library. The name is short for "string-string," meaning it looks for one string inside another.

How strstr Works

The function takes two arguments: strstr(haystack, needle). Instead of returning a simple "Yes" or "No," it returns a pointer.

  1. If the needle is found: It returns a pointer to the very first character of the match inside the haystack. This allows you to see where the phrase starts or even print everything that follows it.
  2. If the needle is NOT found: It returns NULL.

Think of it like a laser pointer. If you ask strstr to find "cat" in the sentence "The caterpillar climbed," it will point directly to the 'c' at the start of "caterpillar."

A Concrete Example

Here is how you check if a specific word exists within a sentence:

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

int main() {
    char haystack[] = "Learning to code in C is exciting!";
    char needle[] = "code";
    char *result;

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

    if (result != NULL) {
        printf("Found it! The match starts at: %s\n", result);
    } else {
        printf("Word not found.\n");
    }

    return 0;
}

In this code, result points to the "c" in "code." When we print %s using that pointer, the computer starts reading from that spot, resulting in the output: Found it! The match starts at: code in C is exciting!.

Why Use It?

Searching is the backbone of most software. Whether you are filtering a list of names, checking if an email address contains an "@" symbol, or scanning a file for a specific keyword, strstr is your primary tool for scanning text data efficiently.

Key takeaway

Use strstr to locate a substring; it returns a pointer to the match if found, and NULL if the search fails.