strncasecmp.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* strncasecmp.c -- case insensitive string comparator
  2. Copyright (C) 1998-1999, 2005-2007, 2009-2012 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 Lesser General Public License as published by
  5. the Free Software Foundation; either version 2, 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 Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program; if not, write to the Free Software Foundation,
  13. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <string.h>
  17. #include <ctype.h>
  18. #include <limits.h>
  19. #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
  20. /* Compare no more than N bytes of strings S1 and S2, ignoring case,
  21. returning less than, equal to or greater than zero if S1 is
  22. lexicographically less than, equal to or greater than S2.
  23. Note: This function cannot work correctly in multibyte locales. */
  24. int
  25. strncasecmp (const char *s1, const char *s2, size_t n)
  26. {
  27. register const unsigned char *p1 = (const unsigned char *) s1;
  28. register const unsigned char *p2 = (const unsigned char *) s2;
  29. unsigned char c1, c2;
  30. if (p1 == p2 || n == 0)
  31. return 0;
  32. do
  33. {
  34. c1 = TOLOWER (*p1);
  35. c2 = TOLOWER (*p2);
  36. if (--n == 0 || c1 == '\0')
  37. break;
  38. ++p1;
  39. ++p2;
  40. }
  41. while (c1 == c2);
  42. if (UCHAR_MAX <= INT_MAX)
  43. return c1 - c2;
  44. else
  45. /* On machines where 'char' and 'int' are types of the same size, the
  46. difference of two 'unsigned char' values - including the sign bit -
  47. doesn't fit in an 'int'. */
  48. return (c1 > c2 ? 1 : c1 < c2 ? -1 : 0);
  49. }