Find a substring of a string in C

This is an example C program for finding a substring of a string using strstr.

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

int main ()
    const char * haystack = "the quick brown fox jumped over the lazy dog";
    const char * needle = "the";
    char * s;
    const char * start;

    start = haystack;
    while (s = strstr (start, needle)) {
        printf ("Found %d characters in.\n", s - haystack);
        start = s + strlen (needle);
    return 0;


The output of the example looks like this:

Found 0 characters in.
Found 32 characters in.

Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer