Strings: Finding a Substring

Dave Sinkula 0 Tallied Votes 152 Views Share

How might I write an implementation in C of the standard library function strstr ? Here's how I might.

What if I need it to be case-insensitive?

#include <stdio.h>

const char *mystrstr(const char *haystack, const char *needle)
{
   if ( !*needle )
   {
      return haystack;
   }
   for ( ; *haystack; ++haystack )
   {
      if ( *haystack == *needle )
      {
         /*
          * Matched starting char -- loop through remaining chars.
          */
         const char *h, *n;
         for ( h = haystack, n = needle; *h && *n; ++h, ++n )
         {
            if ( *h != *n )
            {
               break;
            }
         }
         if ( !*n ) /* matched all of 'needle' to null termination */
         {
            return haystack; /* return the start of the match */
         }
      }
   }
   return 0;
}

int main(void)
{
   const char text[] = "The quick brown fox jumps over the lazy dog.";
   const char word[] = "fox";
   const char *found = mystrstr(text, word);
   if ( found )
   {
      puts(found);
   }
   return 0;
}

/* my output
fox jumps over the lazy dog.
*/