文章目录
- 函数说明
- 函数声明
- 函数参数
- 函数实现
- 函数实例
函数说明
strcasecmp()函数对字符串s1和s2执行逐字节比较,忽略字符的大小写。如果发现s1分别小于、匹配或大于s2,则返回一个小于、等于或大于0的整数。
函数声明
#include <strings.h>
int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t n);
函数参数
函数输入值:
s1 / s2 :对比字符串
n:对比个数
函数返回值:
strcasecmp()函数在忽略大小写后
如果发现si分别小于、匹配或大于s2,则返回一个小于、等于或大于零的整数。
(1)若参数s1和s2字符串相同则返回0
(2)若参数s1大于s2,则返回大于0的值
(3)若参数s1小于s2,则返回小于0的值
函数实现
int
strncasecmp(const char *s1, const char *s2, size_t nch)
{size_t ii;int res = -1;if (!s1) {if (!s2)return 0;return (-1);}if (!s2)return (1);for (ii = 0; (ii < nch) && *s1 && *s2; ii++, s1++, s2++) {res = (int) (tolower(*s1) - tolower(*s2));if (res != 0)break;}if (ii == nch) {s1--;s2--;}if (!*s1) {if (!*s2)return 0;return (-1);}if (!*s2)return (1);return (res);
}int
strcasecmp(const char *s1, const char *s2)
{return strncasecmp(s1, s2, 1000000);
}
函数实例
#include <ctype.h>
#include <string.h>/*
int
strncasecmp_test(const char *s1, const char *s2, size_t nch)
{size_t ii;int res = -1;if (!s1) {if (!s2)return 0;return (-1);}if (!s2)return (1);for (ii = 0; (ii < nch) && *s1 && *s2; ii++, s1++, s2++) {res = (int) (tolower(*s1) - tolower(*s2));if (res != 0)break;}if (ii == nch) {s1--;s2--;}if (!*s1) {if (!*s2)return 0;return (-1);}if (!*s2)return (1);return (res);
}int
strcasecmp_test(const char *s1, const char *s2)
{return strncasecmp_test(s1, s2, 1000000);
}
*/int main()
{int ret;char *a = "aBJbHIUb";char *b = "AbjBh";
// ret = strncasecmp_test(a, b, 3);ret = strncasecmp(a, b, 3);printf("ret = %d\n", ret);return 0;
}
输出结果:
strcasecmp优化后的函数 strncasecmp_test
当*a = “aBJbHIUb”,b = “AbjBh”, 返回值:0
当a = “aBJbHIUb”,b = “Ab”,返回值:1
当a = “aB”,b = “AbjBh”, 返回值:-1
当a =“aB”,b = “Ab”, 返回值:0
当a = “aBJbHIUb”,b = “Ah”, 返回值:-6
当a = “ah”,*b= “AbjBh”, 返回值:6
使用string.h中的strcasecmp
当*a = “aBJbHIUb”,b = “AbjBh”, 返回值:0
当a =“aBJbHIUb”,b = “Ab”,返回值:106
当a = “aB”,b = “AbjBh”, 返回值:-106
当a =“aB”,b = “Ab”, 返回值:0
当a = “aBJbHIUb”,b = “Ah”, 返回值:-6
当a = “ah”,*b= “AbjBh”, 返回值:6