1

I am writing a program to compare a few characters with a Char Array and return the index of the array. Is there any possible way to compare ignore case? For example below:

String in = "I AM A HAPPY BOY";
char[] cha = new char[] {a,c,e,g,i,k,h,m,o,q,s,u,w,y};
char testChar = in.substring(4,5).charAt(0);

for(int a = 0; a<char.length; a++){
   if(cha[a] == testChar)
       return a+1;
}

I am unable to get the index as it will always point to 0. Is there anyway to ignore case here? Appreciate some advise.

Daniel
  • 75
  • 4
  • 9

4 Answers4

5

Use Character.toLowerCase on both characters:

if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
    // logic here
}

As a side note, you could get away with the first toLowerCase if all the characters in your array are already lower case, or even use toLowerCase on the initial string and avoid both.

Grim
  • 1,608
  • 9
  • 12
2

You can use Character.toLowerCase(char):

if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
   return a+1;
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

use Character.ToLowerCase(char c) before testing for equality.

Porkbutts
  • 924
  • 7
  • 12
-1

in=in.toLowerCase();

However the most efficient way to convert chars between cases is to flip the 6th bit (ASCII values differ by 32).

klj
  • 1
  • Java does not work on _ASCII_. It works on [Unicode](http://docs.oracle.com/javase/tutorial/i18n/text/unicode.html). However 32 difference does apply to english alphabates. – Smit Apr 02 '13 at 19:21