The Pragmatic Addict

Making strcasestr work in C

strcasestr is a wonderful function which finds the first occurrence of the substring needle in the string haystack.

Getting there is interesting. First in linux (gcc), this is considered a nonstandard extension, a special define needs to be done. This function does not exist in mingw.

Here are two ways to get around this issue:

Using the Pre-Processor

Please note the _GNU_SOURCE define needs to come before including string.h

#ifdef __MINGW32__
    #include <shlwapi.h>
    #define strcasestr StrStrI
#else
    #define _GNU_SOURCE
    #include <string.h>
#endif

Using code

This code is not optimized but will get by in a pinch.

#include <ctype.h>
char *strcasestr(const char *haystack, const char *needle)
{
   while (*haystack)
   {
      char *Begin = haystack;
      char *pattern = needle;
      while (*haystack && *pattern && (tolower(*haystack) == tolower(*pattern)))
      {
         haystack++;
         pattern++;
      }
      if (!*pattern) return Begin;
      haystack = Begin + 1;
   }
   return NULL;
}

Created: 2024-04-13 Modified: 2024-06-11