Comparing chars in Java

后端 未结 12 492
梦如初夏
梦如初夏 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: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...");
    

提交回复
热议问题