Comparing chars in Java

2019-01-08 10:20发布

It's been a while since I've done any Java so my syntax is not the greatest at the moment.

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

12条回答
霸刀☆藐视天下
2楼-- · 2019-01-08 10:58

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?]")) {
    // ...
}
查看更多
乱世女痞
3楼-- · 2019-01-08 11:00

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))...
查看更多
Rolldiameter
4楼-- · 2019-01-08 11:01

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;
查看更多
Evening l夕情丶
5楼-- · 2019-01-08 11:04

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) { ... }
查看更多
家丑人穷心不美
6楼-- · 2019-01-08 11:05

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.

查看更多
放我归山
7楼-- · 2019-01-08 11:07

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...");
查看更多
登录 后发表回答