问题描述
我目前正在评估两个不区分大小写的实现
字符串比较函数来替换非ANSI stricmp()。两个以下的实现似乎都运行正常,但我想知道一个是否比另一个更好或者是否有某种混合的 b br />
这将是优越的。
实施1:
#ifndef HAVE_STRCASECMP
#define ccmp( a,b)((a)==(b)?0:((a)>(b)?1:-1))
int strcasecmp(unsigned char * s1,unsigned char * s2)
{
unsigned char c1,c2;
for(;;)
{
if(* s1 ==''\'''|| * s2 ==''\''')
返回ccmp(* s1,* s2) ;
c1 =(isascii(* s1)&& isupper(* s1))? (unsigned char)tolower(* s1):
* s1;
c2 =(isascii(* s2)&& isupper(* s2))? (unsigned char)tolower(* s2):
* s2;
if(c1!= c2)
返回ccmp(c1,c2) );
s1 ++;
s2 ++;
}
}
#undef ccmp
#endif
实施2:
int strcasecmp(const char * s1,const char * s2)
{
unsigned char c1,c2;
do {
c1 = * s1 ++;
c2 = * s2 ++;
c1 =(unsigned char)tolower((unsigned char)c1);
c2 =(unsigned char)tolower((unsigned char)c2 );
}
while((c1 == c2)&&(c1!=''\'''));
return(int)c1-c2;
}
I''m currently evaluating two implementations of a case insensitive
string comparison function to replace the non-ANSI stricmp(). Both of
the implementations below seem to work fine but I''m wondering if one is
better than the other or if there is some sort of hybrid of the two
that would be superior.
IMPLEMENTATION 1:
#ifndef HAVE_STRCASECMP
#define ccmp(a,b) ((a) == (b) ? 0 : ((a) > (b) ? 1 : -1))
int strcasecmp(unsigned char *s1, unsigned char *s2)
{
unsigned char c1, c2;
for ( ; ; )
{
if (*s1 == ''\0'' || *s2 == ''\0'')
return ccmp(*s1,*s2);
c1= (isascii(*s1) && isupper(*s1)) ? (unsigned char) tolower(*s1) :
*s1;
c2= (isascii(*s2) && isupper(*s2)) ? (unsigned char) tolower(*s2) :
*s2;
if (c1 != c2)
return ccmp(c1,c2);
s1++;
s2++;
}
}
#undef ccmp
#endif
IMPLEMENTATION 2:
int strcasecmp(const char *s1, const char *s2)
{
unsigned char c1,c2;
do {
c1 = *s1++;
c2 = *s2++;
c1 = (unsigned char) tolower( (unsigned char) c1);
c2 = (unsigned char) tolower( (unsigned char) c2);
}
while((c1 == c2) && (c1 != ''\0''));
return (int) c1-c2;
}
推荐答案
怎么样 :
int strcasecmp(const char * s1,const char * s2)
{
while(1)
{
int c1 = tolower((unsigned char)* s1 ++);
int c2 = tolower ((unsigned char)* s2 ++);
如果(c1 == 0 || c1!= c2)返回c1 - c2;
}
}
不重复使用变量,没有iffy强制转换,略短。
我错过了什么?
-
Chris" one-track" Dollin
功能并不意味着必要。
How about:
int strcasecmp( const char *s1, const char *s2 )
{
while (1)
{
int c1 = tolower( (unsigned char) *s1++ );
int c2 = tolower( (unsigned char) *s2++ );
if (c1 == 0 || c1 != c2) return c1 - c2;
}
}
Doesn''t reuse variables, doesn''t have iffy casts, slightly shorter.
What have I missed?
--
Chris "one-track" Dollin
Capability does not imply necessity.
从什么时候str *函数应该处理NULL?
- - 理查德
Since when were the str* functions supposed to handle NULL?
-- Richard
这篇关于比较两个strcasecmp(stricmp)实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!