Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

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, 2025 by avibootz
...