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;
}

Download it here.

The output of the example looks like this:

Found 0 characters in.
Found 32 characters in.

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer