How to compare character ignoring case in primitive types

Arush Kamboj picture Arush Kamboj · Apr 19, 2012 · Viewed 113.9k times · Source

I am writing these lines of code:

String name1 = fname.getText().toString();
String name2 = sname.getText().toString();
aru = 0;

count1 = name1.length();
count2 = name2.length();
for (i = 0; i < count1; i++)
{  
    for (j = 0; j < count2; j++)
    { 
        if (name1.charAt(i)==name2.charAt(j))
            aru++;
    }
    if(aru!=0)
        aru++;
}

I want to compare the Characters of two Strings ignoring the case. Simply using IgnoreCase doesn't work. Adding '65' ASCII value doesn't work either. How do I do this?

Answer

Shehzad picture Shehzad · Apr 19, 2012

The Character class of Java API has various functions you can use.

You can convert your char to lowercase at both sides:

Character.toLowerCase(name1.charAt(i)) == Character.toLowerCase(name2.charAt(j))

There are also a methods you can use to verify if the letter is uppercase or lowercase:

Character.isUpperCase('P')
Character.isLowerCase('P')