Search code examples
cstringcase-insensitive

Case insensitive comparison of constant strings


I'm trying to use this function to compare two strings, case insensitively.

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

I have the copy piece correct, yet the case sensitive portion is giving me some trouble as const is a constant, thus read only, making these fail:

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

Both chars must remain const, otherwise I think this would work... So my question: is there a way to ignore capitalization while keeping the char-strings const?


Solution

  • You could use a temporary char variable:

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