How to create the function: stristr() to find case insensitive word in string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h> 

const char *stristr(const char *haystack, const char *needle);

int main(void)
{
    char sentence[50] = "Linux c programming";
    char word[20] = "Linux";
    
    if (stristr(sentence, word) != NULL)
        printf("Found\n"); // Found
    else
        printf("NOT Found\n");
    
    if (stristr(sentence, "LINUX") != NULL)
        printf("Found\n"); // Found
    else
        printf("NOT Found\n");
    
    return 0;
}
const char *stristr(const char *haystack, const char *needle)
{
    const char *h, *n;
    
    if (!*needle)
        return haystack;

    for (; *haystack; haystack++)
    {
        if (tolower(*haystack) == tolower(*needle))
        {
            for (h = haystack, n = needle; *h && *n; h++, n++)
            {
                if (tolower(*h) != tolower(*n) )
                    break;
            }
            if (!*n) // if *n is NULL = end of 'needle' = found 
                return haystack; // start of the match
        }
    }
    return 0; // NOT found
}


/*
run:

Found
Found

*/


answered Oct 28, 2014 by avibootz
...