[Libclc-developers] libclc: New function for the string module?
Status: Planning
Brought to you by:
augestad
From: <bo...@me...> - 2003-06-06 15:57:08
|
Hello. Below is the source code for a function I needed at work today. Since it is pretty general, it might be a candidate for the clc_string module? The function is a case insensitive version of strstr(), with one exception: I didn't have the stomach to let the function return a char* like strstr() does. ;-) Please suggest a new name for the function, I'm only semi happy about the current clc_strcasestr(), but couldn't come up with anything better. Bjørn /* $Id: $ */ /* * Copyright(c) 2003, B. Augestad, bo...@me... * COPYING RESTRICTIONS APPLY, see COPYING file. */ #include <ctype.h> #include <string.h> #include "clc_assert.h" #include "clc_string.h" const char* clc_strcasestr(const char *haystack, const char *needle) { size_t cb1, cb2; const char *start, *stop, *org_needle = needle; int c1, c2; clc_assert_not_null(clc_strcasestr, haystack); clc_assert_not_null(clc_strcasestr, needle); cb1 = strlen(haystack); cb2 = strlen(needle); /* The standard says that empty needles, "", returns haystack. */ if(cb2 == 0) return haystack; /* No point in finding needles bigger than haystack */ if(cb2 > cb1) return NULL; /* Compute the last starting point of a possible match */ start = haystack; stop = start + cb1 - cb2; /* Now compare strings */ while(start <= stop) { needle = org_needle; haystack = start; for (;; haystack++, needle++) { c1 = tolower((int)*haystack); c2 = tolower((int)*needle); /* If end of needle */ if (c2 == '\0') return start; else if(c1 != c2) break; } start++; } return NULL; } #ifdef CLC_STRCASESTR_TEST int main(void) { const char *s; /* Legal variants */ s = clc_strcasestr("A", "A"); clc_assert(main, s != NULL); s = clc_strcasestr("AAA", "A"); clc_assert(main, s != NULL); s = clc_strcasestr("AAA", "a"); clc_assert(main, s != NULL); s = clc_strcasestr("AAB", "B"); clc_assert(main, s != NULL); s = clc_strcasestr("AAB", "b"); clc_assert(main, s != NULL); s = clc_strcasestr("AABcdEfGhIj123", "bcdefg"); clc_assert(main, s != NULL); s = clc_strcasestr("AAA", ""); clc_assert(main, s != NULL); s = clc_strcasestr("AA1AA2AA3", "AA2"); clc_assert(main, s != NULL); /* Illegal variants */ s = clc_strcasestr("AAA", "x"); clc_assert(main, s == NULL); s = clc_strcasestr("AAA", "AAAAAA"); clc_assert(main, s == NULL); return 0; } #endif |