Anthony
Anthony

Reputation: 69

How to compare two characters without case sensitivity in C?

I am trying to compare two specific characters in two strings,but I want to make the comparing without case sensitivity. How can I do this?

right now I am using a code like that:

if (str1[i]==str2[j]) printf("Equal");

but I want to do this without case sensivity.

Thank you in advance for taking your time to help!

Upvotes: 2

Views: 1996

Answers (2)

BEPP
BEPP

Reputation: 955

We can achieve your requirement by converting both of the character to either upper or lower case character using toupper() or tolower().

Example:

#include <stdio.h>
#include <ctype.h> //For tolower()

int main()
{
    char str1[]="Time", str2[]="time";
    /*
     * Just for an example i am comparing the first char
     * from 2 different strings.
     */
    if(tolower(str1[0]) ==tolower(str2[0])) {
        printf("Char's are equal\n");
    }
    else {
        printf("Char's are not equal");
    }
    return 0;
}

Output:

Char's are equal

Upvotes: 1

Alex
Alex

Reputation: 1021

You can use low case for both chars, for example by using tolower function:

if (tolower(str1[i])==tolower(str2[j])) printf("Equal");

Also keep in mind: tolower does not work for multibyte char. So for those chars you should use other function

Upvotes: 6

Related Questions