How to create a case-insensitive version of the strstr function for substring search in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h> // tolower

char* strstrcaseinsensitive(const char* haystack, const char* needle) {
    if (!*needle) {
        return (char*) haystack;
    }
    
    for (const char* h = haystack; *h; h++) {
        if (tolower((unsigned char)*h) == tolower((unsigned char)*needle)) {
            const char* sub = h;
            const char* n = needle;
            while (*sub && *n && tolower((unsigned char)*sub) == tolower((unsigned char)*n)) {
                sub++;
                n++;
            }
            if (!*n) {
                return (char*) h;
            }
        }
    }
    
    return NULL;
}

int main() {
    const char* haystack = "C is a general-purpose programming language";
    const char* needle = "PROGRAMMING";
    
    char* result = strstrcaseinsensitive(haystack, needle);
    if (result) {
        printf("Found: %s\n", result);
    } else {
        printf("Not Found\n");
    }

    return 0;
}


       
/*
run:
    
Found: programming language
   
*/

 



answered Feb 4 by avibootz
...