常量字符串的不区分大小写

时间:2012-07-10 02:07:18

标签: c string case-insensitive

我正在尝试使用此函数来比较两个字符串,不区分大小写。

int strcasecmp(const char *x1, const char *x2);

我的副本片段是正确的,但是区分大小写的部分给了我一些麻烦,因为const是一个常数,因此只读,导致这些失败:

*x1 = (tolower(*x1)); // toupper would suffice as well, I just chose tolower
*x2 = (tolower(*x2)); // likewise here

两个字符必须保持const,否则我认为这样可行...... 所以我的问题是:有没有办法在保留char - 字符串const的同时忽略大小写?

2 个答案:

答案 0 :(得分:2)

您可以使用临时char变量:

char c1 = tolower(*x1);
char c2 = tolower(*x2);

if (c1 == c2)
 ...

答案 1 :(得分:2)

当然 - 您可以在tolower声明中比较if的结果:

while (*x1 && *x2 && tolower(*x1) == tolower(*x2)) {
    x1++;
    x2++;
}
return tolower(*x1)-tolower(*x2);
相关问题