我试图从linux源代码中理解strnicmp的实现。 http://lxr.free-electrons.com/source/lib/string.c
我只是尝试在没有额外变量 c1 和 c2 的情况下实现它,并在 while 中添加了一些条件。
int StrNiCmp(const char *s1, const char *s2, size_t len)
{
if(!len)
return 0;
do {
if(!(*s1) || !(*s2))
break;
if(*s1 == *s2)
continue;
if(ToLower(*s1) != (ToLower(*s2)))
break;
} while(len-- && *s1++ && *s2++) ;
return (int)(*s1) - (int)(*s2);
}
所以我的疑问是上面的实现有任何潜在的错误。 我检查了一些基本测试用例以验证其功能是否正常。没有任何额外变量是个好主意
最佳答案
与官方实现相比,这节省了 1 个寄存器。这是我的想法,只用一些简单的案例进行了测试。
int StrNiCmp(const char *s1, const char *s2, size_t len)
{
int diff = 0;
while (!diff && len-- && *s1 && *s2) {
if (*s1 != *s2)
diff = (int)ToLower(*s1) - (int)ToLower(*s2);
s1++;
s2++;
}
return diff;
}
这个可能会稍微更有效率:
int StrNiCmp(const char *s1, const char *s2, size_t len)
{
int diff = 0;
while (len-- && *s1 && *s2) {
if (*s1 != *s2)
if (diff = (int)ToLower(*s1) - (int)ToLower(*s2))
break;
s1++;
s2++;
}
return diff;
}
关于c - strnicmp在c中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40988538/