How might I write an implementation in C a case-insensitive version of the standard library function strstr
? Here's how I might.
Strings: Case Insensitive strstr
#include <stdio.h>
#include <ctype.h>
const char *mystristr(const char *haystack, const char *needle)
{
if ( !*needle )
{
return haystack;
}
for ( ; *haystack; ++haystack )
{
if ( toupper(*haystack) == toupper(*needle) )
{
/*
* Matched starting char -- loop through remaining chars.
*/
const char *h, *n;
for ( h = haystack, n = needle; *h && *n; ++h, ++n )
{
if ( toupper(*h) != toupper(*n) )
{
break;
}
}
if ( !*n ) /* matched all of 'needle' to null termination */
{
return haystack; /* return the start of the match */
}
}
}
return 0;
}
int main(void)
{
const char text[] = "The quick brown fox jumps over the lazy dog.";
const char word[] = "FoX";
const char *found = mystristr(text, word);
if ( found )
{
puts(found);
}
return 0;
}
/* my output
fox jumps over the lazy dog.
*/
c_coder 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.