Comparing chars in Java

JavaComparisonChar

Java Problem Overview


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.)

Java Solutions


Solution 1 - Java

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?]")) {
    // ...
}

Solution 2 - Java

If you know all your 21 characters in advance you can write them all as one String and then check it like this:

char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;

I think this is the shortest way.

Solution 3 - Java

The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)

Your second statement is correct, but you will have 21 ORs.

If the 21 characters are "consecutive" the above solutions is fine.

If not you can pre-compute a hash set of valid characters and do something like

if (validCharHashSet.contains(symbol))...

Solution 4 - Java

you can use this:

if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))

note that you do not need to create a separate String with the letters A-Z.

Solution 5 - Java

It might be clearer written as a switch statement with fall through e.g.

switch (symbol){
    case 'A':
    case 'B':
      // Do stuff
      break;
     default:
}

Solution 6 - Java

If you have specific chars should be:

Collection<Character> specificChars = Arrays.asList('A', 'D', 'E');  // more chars
char symbol = 'Y';
System.out.println(specificChars.contains(symbol));   // false
symbol = 'A';
System.out.println(specificChars.contains(symbol));   // true			

Solution 7 - Java

Using Guava:

if (CharMatcher.anyOf("ABC...").matches(symbol)) { ... }

Or if many of those characters are a range, such as "A" to "U" but some aren't:

CharMatcher.inRange('A', 'U').or(CharMatcher.anyOf("1379"))

You can also declare this as a static final field so the matcher doesn't have to be created each time.

private static final CharMatcher MATCHER = CharMatcher.anyOf("ABC...");

Solution 8 - Java

Option 2 will work. You could also use a Set<Character> or

char[] myCharSet = new char[] {'A', 'B', 'C', ...};
Arrays.sort(myCharSet);
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }

Solution 9 - Java

Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.

Alternatively you could put your valid values into an array and check for the existence of symbol in the array.

Solution 10 - Java

pseudocode as I haven't got a java sdk on me:

Char candidates = new Char[] { 'A', 'B', ... 'G' };

foreach(Char c in candidates)
{
    if (symbol == c) { return true; }
}
return false;

Solution 11 - Java

You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

Solution 12 - Java

One way to do it using a List<Character> constructed using overloaded convenience factory methods in [tag:java9] is as :

if(List.of('A','B','C','D','E').contains(symbol) {
    // do something
}

Solution 13 - Java

You can solve this easily by using the String.indexOf(char) method which returns -1 if the char is not in the String.

String candidates = "ABCDEFGHIJK";
if(candidates.indexOf(symbol) != -1){
    //character in list of candidates
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavaMark ByersView Answer on Stackoverflow
Solution 2 - JavaMarcView Answer on Stackoverflow
Solution 3 - JavaAlvinView Answer on Stackoverflow
Solution 4 - JavaDaniel HeView Answer on Stackoverflow
Solution 5 - JavaRichard MiskinView Answer on Stackoverflow
Solution 6 - JavalukastymoView Answer on Stackoverflow
Solution 7 - JavaColinDView Answer on Stackoverflow
Solution 8 - JavarlibbyView Answer on Stackoverflow
Solution 9 - JavaEndophageView Answer on Stackoverflow
Solution 10 - JavatenpnView Answer on Stackoverflow
Solution 11 - JavaAnonyView Answer on Stackoverflow
Solution 12 - JavaNamanView Answer on Stackoverflow
Solution 13 - JavaMouhamadou Lamine GueyeView Answer on Stackoverflow