Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing chars in Java

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.) 
like image 763
Alex Avatar asked Feb 17 '11 20:02

Alex


1 Answers

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?]")) {     // ... } 
like image 170
Mark Byers Avatar answered Sep 20 '22 17:09

Mark Byers