Home

How Does the strstr Function Work in C?

Searching for a specific word or phrase inside a longer text is one of the most fundamental operations when working with strings. In the C programming language, we use the strstr function from the <string.h> library for this purpose.

Let’s look at a simple program that demonstrates how this function works in practice, how to interpret its result, and how to calculate the exact position (index) of the found word.

Program Code with Comments

Here is a simple C script to illustrate that point, complete with a thorough breakdown of each line:

#include <stdio.h>   // Standard input/output library (needed for printf)
#include <string.h>  // String manipulation library (needed for strstr)

int main() {
    // Define the main text (string) where we want to search
    const char *tekst = "Witaj świecie, programowanie w C jest super!";

    // Define the substring we are looking for
    const char *szukane = "programowanie";

    // The strstr function searches for 'szukane' inside 'tekst'.
    // If found, it returns a pointer (memory address) to the start of the matching word within the main text.
    // If not found, it returns NULL.
    char *wynik = strstr(tekst, szukane);

    // Check if the strstr function actually found anything (i.e., the result is not NULL)
    if (wynik != NULL) {
        // Print the text starting from the found match all the way to the end of the string
        printf("Znaleziono podciąg od słowa: %s\n", wynik);
    } else {
        // Inform the user if the searched phrase does not exist in the text
        printf("Nie znaleziono podciągu.\n");
    }

    // Calculate the index (position) of the found word.
    // We subtract the starting address of the main text (tekst) from the address returned by strstr (wynik).
    // The difference between these two pointers gives us the number of characters (index), which we cast to an (int).
    int indeks = (int)(wynik - tekst);

    // Displaying the summary on the screen
    printf("Tekst: %s\n", tekst);
    printf("Szukany substring: %s\n", szukane);
    printf("indeks: %d\n", indeks); // This will print the index number (0-indexed)

    return 0; // Successful program termination
}

Key Takeaways from This Code

Tags: CStringPointers