CodexBloom - Programming Q&A Platform

advanced patterns in custom `strstr` implementation for case-insensitive search in C

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
c string case-insensitivity C

I'm working on a personal project and I'm trying to implement a custom version of `strstr` that performs a case-insensitive search for a substring within a string. However, I'm working with unexpected behavior where the function sometimes fails to find matches that I believe should be found. Here's my implementation: ```c #include <stdio.h> #include <string.h> #include <ctype.h> char *stristr(const char *haystack, const char *needle) { if (!*needle) return (char *)haystack; for (; *haystack; haystack++) { if (tolower(*haystack) == tolower(*needle)) { const char *h = haystack, *n = needle; while (*h && *n && tolower(*h) == tolower(*n)) { h++; n++; } if (!*n) return (char *)haystack; } } return NULL; } ``` I tested the function with this code: ```c int main() { const char *text = "Hello World! This is a Test String."; const char *sub = "test"; char *result = stristr(text, sub); if (result) { printf("Found: %s\n", result); } else { printf("Not found\n"); } return 0; } ``` While I expect the output to be "Found: Test String." it prints "Not found" instead. I've confirmed that the substring exists in the string, and I've also tried using both lower and upper case variations of the `haystack` and `needle`. I suspect there might be a logic behavior in the way I'm iterating through the characters, but I need to pinpoint it. Any insights on why this might not be working as intended would be greatly appreciated! I'm using GCC version 10.2 on Ubuntu 20.04. My development environment is macOS. Has anyone else encountered this? This is part of a larger application I'm building. How would you solve this?