strcasecmp.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Case-insensitive string comparison function.
  2. Copyright (C) 1998-1999, 2005-2007, 2009-2017 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <string.h>
  16. #include <ctype.h>
  17. #include <limits.h>
  18. #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
  19. /* Compare strings S1 and S2, ignoring case, returning less than, equal to or
  20. greater than zero if S1 is lexicographically less than, equal to or greater
  21. than S2.
  22. Note: This function does not work with multibyte strings! */
  23. int
  24. strcasecmp (const char *s1, const char *s2)
  25. {
  26. const unsigned char *p1 = (const unsigned char *) s1;
  27. const unsigned char *p2 = (const unsigned char *) s2;
  28. unsigned char c1, c2;
  29. if (p1 == p2)
  30. return 0;
  31. do
  32. {
  33. c1 = TOLOWER (*p1);
  34. c2 = TOLOWER (*p2);
  35. if (c1 == '\0')
  36. break;
  37. ++p1;
  38. ++p2;
  39. }
  40. while (c1 == c2);
  41. if (UCHAR_MAX <= INT_MAX)
  42. return c1 - c2;
  43. else
  44. /* On machines where 'char' and 'int' are types of the same size, the
  45. difference of two 'unsigned char' values - including the sign bit -
  46. doesn't fit in an 'int'. */
  47. return (c1 > c2 ? 1 : c1 < c2 ? -1 : 0);
  48. }