strcasecmp,strncasecmp函数实现——strings.h库函数
信息来自RHEL,man page:STRCASECMP(3)Linux Programmer's ManualSTRCASECMP(3)NAMEstrcasecmp, strncasecmp - compare two strings ignorin
·
strcasecmp和strncasecmp函数相当于windows下的stricmp和strnicmp函数!
信息来自RHEL,man page:
STRCASECMP(3) Linux Programmer's Manual STRCASECMP(3)
NAME
strcasecmp, strncasecmp - compare two strings ignoring case
SYNOPSIS
#include <strings.h>
int strcasecmp(const char *s1, const char *s2);
int strncasecmp(const char *s1, const char *s2, size_t n);
DESCRIPTION
The strcasecmp() function compares the two strings s1 and s2, ignoring the case of the characters. It returns
an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match,
or be greater than s2.
The strncasecmp() function is similar, except it compares the only first n bytes of s1.
RETURN VALUE
The strcasecmp() and strncasecmp() functions return an integer less than, equal to, or greater than zero if s1
(or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
CONFORMING TO
4.4BSD, POSIX.1-2001.
函数实现:
strcasecmp()函数实现:
0.功能描述:
功能参照strcmp(传送门:http://blog.csdn.net/riyadh_linux/article/details/50021381)函数,区别之处在于该函数比对时不区分大小写。
字符串比较函数,
逐字符
比较字符串s1(source)
和字符串s2(dest)
:
源字符串大于
目标字符串时—-> 返回字符串s1从前往后第一个大于字符串s2的对应字符ASCII差值(为正)
源字符串小于
目标字符串时—-> 返回字符串s1从前往后第一个小于字符串s2的对应字符ASCII差值(为负)
源字符串等于
目标字符串时—-> 返回0
1.原型:
#include <strings.h>
int strcasecmp(const char *s1, const char *s2);
2.参数:
s1即源字符串。
s2目标字符串。
3.实现:
//定义FALSE宏值
#define FALSE ('Z' - 'A')
#define DIFF_VALUE ('a' - 'A')
int my_strcasecmp(const char *s1, const char *s2)
{
int ch1 = 0;
int ch2 = 0;
//参数判断
if(NULL == s1 || NULL == s2){
return FALSE;
}
//逐个字符查找比对,并记录差值
do{
if((ch1 = *((unsigned char *)s1++)) >= 'A' && ch1 <= 'Z'){
*s1 += DIFF_VALUE;
}
if((ch2 = *((unsigned char *)s2++)) >= 'A' && ch2 <= 'Z'){
*s2 += DIFF_VALUE;
}
}while(ch1 && ch1 == ch2);
return ch1 - ch2;
}
strncasecmp()函数实现:
0.功能描述:
参照strcasecmp函数,区别之处在于,逐个字符比对,判断前n个字符。并且当n为零时,返回为零
1.原型:
#include <strings.h>
int my_strncasecmp(const char *s1, const char *s2, size_t n)
2.参数:
s1,s2:对应strcasecmp函数
n:用来标示此函数应对比前n个字符
3.实现:
#define DIFF_VALUE ('a' - 'A')
#define FALSE ('z' - 'A')
int my_strncmp(const char *s1, const char *s2, size_t n)
{
int ch1 = 0;
int ch2 = 0;
if(NULL == s1 || NULL == s2 || 0 > n){
return FALSE;
}
if(0 == n){
return 0;
}
do{
if((ch1 = *(unsigned char *)s1++) >= 'A' && (ch1 <= 'Z')){
ch1 += DIFF_VALUE;
}
if((ch2 = *(unsigned char *)s2++) >= 'A' && (ch2 <= 'Z'))
}while(n-- && ch1 && (ch1 == ch2));
return ch1 - ch2;
}
=============文章结束==============
小菜总结,如有不当,欢迎批评!
更多推荐
已为社区贡献1条内容
所有评论(0)