Search code examples
cstringstring-comparisoncase-insensitivestrcmp

How to do a case-insensitive string comparison?


I want to do a case-insensitive string comparison. What would be the easiest way to accomplish that? I have the below code which performs a case-sensitive operation.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char *str1 = "String";
    char *str2 = "STRING";

    if (strncmp(str1, str2, 100) != 0)
    {
        printf("=(");
        exit(EXIT_FAILURE);
    }

    return 0;
}

Solution

  • If you can afford deviating a little from strict C standard, you can make use of strcasecmp(). It is a POSIX API.

    Otherwise, you always have the option to convert the strings to a certain case (UPPER or lower) and then perform the normal comparison using strcmp().