Comparing chars in Java

Alex picture Alex · Feb 17, 2011 · Viewed 478.3k times · Source

I want to check a char variable is one of 21 specific chars, what is the shortest way I can do this?

For example:

if(symbol == ('A'|'B'|'C')){}

Doesn't seem to be working. Do I need to write it like:

if(symbol == 'A' || symbol == 'B' etc.)

Answer

Mark Byers picture Mark Byers · Feb 17, 2011

If your input is a character and the characters you are checking against are mostly consecutive you could try this:

if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
    // ...
}

However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:

if (symbol.matches("[A-Z?]")) {
    // ...
}

If you have a character you'll first need to convert it to a string before you can use a regular expression:

if (Character.toString(symbol).matches("[A-Z?]")) {
    // ...
}