为什么要单独实现一个 “strncasecmp” 函数呢?这是由于,不同的GCC及库环境略微有些不同,比如在 AARCH64+GCC 上面编译就可能找不到头文件及符号,但 “X86_64+GCC上面可以正确编译”,而 Windows 上面呢,函数名不是 strcasecmp、strncasecmp,而是 “strimcp” “strnicmp” 这两个C函数(msvcrt.dll)。
#ifndef strcasecmp
#define strcasecmp strcasecmp_
#endif
#ifndef strncasecmp
#define strncasecmp strncasecmp_
#endif
inline int strncasecmp_(const void* x, const void* y, size_t length) noexcept {
if (x == y || length == 0) {
return 0;
}
char* px = (char*)x;
char* py = (char*)y;
for (size_t i = 0; i < length; i++) {
int xch = toupper(*px++);
int ych = toupper(*py++);
if (xch != ych) {
return xch > ych ? 1 : -1;
}
}
return 0;
}
inline int strcasecmp_(const void* x, const void* y) noexcept {
if (x == y) {
return 0;
}
char* px = (char*)x;
char* py = (char*)y;
size_t xlen = strlen(px);
size_t ylen = strlen(py);
if (xlen != ylen) {
return xlen > ylen ? 1 : -1;
}
return strncasecmp(x, y, xlen);
}