Comparing chars in Java

后端 未结 12 485
梦如初夏
梦如初夏 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:47

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

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

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

    switch (symbol){
        case 'A':
        case 'B':
          // Do stuff
          break;
         default:
    }
    
    0 讨论(0)
  • 2020-11-29 22:50

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

    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.

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

    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;
    
    0 讨论(0)
提交回复
热议问题