Strings: Case Insensitive strstr

Dave Sinkula 0 Tallied Votes 1K Views Share

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

But I need it to be case-sensitive?

#include <stdio.h>
#include <ctype.h>

const char *mystristr(const char *haystack, const char *needle)
{
   if ( !*needle )
   {
      return haystack;
   }
   for ( ; *haystack; ++haystack )
   {
      if ( toupper(*haystack) == toupper(*needle) )
      {
         /*
          * Matched starting char -- loop through remaining chars.
          */
         const char *h, *n;
         for ( h = haystack, n = needle; *h && *n; ++h, ++n )
         {
            if ( toupper(*h) != toupper(*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 = mystristr(text, word);
   if ( found )
   {
      puts(found);
   }
   return 0;
}

/* my output
fox jumps over the lazy dog.
*/
c_coder 0 Newbie Poster

Mr Dave...You have posted very neat C programs..Thanks a bunch...Even though i knew how to solve most of them it was nice to learn a much better way of solving them...It has been of a big help...
c_coder

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.