The Pragmatic Addict

Adding strcasestr to MinGW

Porting gcc code to Windows using MinGW is not without it challenges. Every now and then you run into a linux only function that you wished were in windows. Enter strcasestr

It’s a very useful string.h function that can locate a substring with case-insensitve matching.

Here are two ways to get around this issue:

Using Pre-Processor Define

This define will call the windows version of strcasestr.

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

Using code

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

#ifdef __MINGW32__
#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;
}
#endif

Created: 2024-04-13 Modified: 2024-04-12