1 /* Case-insensitive searching in a string.
2 Copyright (C) 2005-2007 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2005.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 #include <stddef.h> /* for NULL, in case a nonstandard string.h lacks it */
27 #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
29 /* Find the first occurrence of NEEDLE in HAYSTACK, using case-insensitive
31 Note: This function may, in multibyte locales, return success even if
32 strlen (haystack) < strlen (needle) ! */
34 strcasestr (const char *haystack, const char *needle)
38 /* Speed up the following searches of needle by caching its first
40 unsigned char b = TOLOWER ((unsigned char) *needle);
45 if (*haystack == '\0')
48 if (TOLOWER ((unsigned char) *haystack) == b)
49 /* The first character matches. */
51 const char *rhaystack = haystack + 1;
52 const char *rneedle = needle;
54 for (;; rhaystack++, rneedle++)
58 return (char *) haystack;
59 if (*rhaystack == '\0')
62 if (TOLOWER ((unsigned char) *rhaystack)
63 != TOLOWER ((unsigned char) *rneedle))
64 /* Nothing in this round. */
71 return (char *) haystack;