函数名: strnicmp
功 能: 比较字符串str1和str2的前n个字符串字典序的大小,但是不区分字母大小写。
返回值: 当str1<str2时,返回值<0 ; 当str1=str2时,返回值=0; 当str1>str2时,返回值>0。
比较是这样进行的,先比较2个字符串的第1个字符字典序的大小,如果能比较出大小,则马上返回了,如果不能区别大小,开始比较第2个,如果这时第1个字符串已经到尽头了,第2个字符串还有字符,这时算第2个字符串大。
用 法: int strnicmp(char *str1, char *str2, unsigned maxlen);
#include <stdio.h>
#include <ctype.h>
/**
* strnicmp - Case insensitive, length-limited string comparison
* @s1: One string
* @s2: The other string
* @len: the maximum number of characters to compare
*/
int strnicmp(const char *s1, const char *s2, size_t len)
{
/* Yes, Virginia, it had better be unsigned */
unsigned char c1, c2;
if (!len)
return 0;
do {
c1 = *s1++;
c2 = *s2++; //字符串字串同时后移
if (!c1 || !c2)
break; //如果是空字符,跳出
if (c1 == c2)
continue;
c1 = tolower(c1);
c2 = tolower(c2);
if (c1 != c2)
break;
} while (--len);
return (int)c1 - (int)c2;
}
int main(void)
{
char *buf1 = "BBBccc", *buf2 = "bbbccc";
int nResult;
nResult = strnicmp(buf2, buf1, 3);
if (nResult > 0)
{
printf("buffer 2 is greater than buffer 1\n");
}
if (nResult < 0)
{
printf("buffer 2 is less than buffer 1\n");
}
if (nResult == 0)
{
printf("buffer 2 equals buffer 1\n");
}
return 0;
}