Comparing chars in Java

后端 未结 12 484
梦如初夏
梦如初夏 2020-11-29 22:09

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\')){}         


        
相关标签:
12条回答
  • 2020-11-29 22:30

    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.

    0 讨论(0)
  • 2020-11-29 22:33

    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           
    
    0 讨论(0)
  • 2020-11-29 22:36

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

    if(List.of('A','B','C','D','E').contains(symbol) {
        // do something
    }
    
    0 讨论(0)
  • 2020-11-29 22:38

    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))...
    
    0 讨论(0)
  • 2020-11-29 22:46

    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.

    0 讨论(0)
  • 2020-11-29 22:47

    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?]")) {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题