比较Java中的字符 [英] Comparing chars in Java
问题描述
我想检查一个字符变量是否是一个字符串,因为我已经做了任何Java,所以我的语法不是最大的。
例如:
if(symbol ==('A'|'B'|'C')){}
b $ b
似乎不工作。我需要像这样写:
if(symbol =='A'|| symbol =='B' )
如果输入是字符,正在检查是否大致连续,您可以尝试这样:
if((symbol> ='A'&& < ='Z')|| symbol =='?'){
// ...
}
然而,如果你的输入是一个字符串,一个更紧凑的方法(但是更慢)是使用一个带有字符类的正则表达式:
if(symbol.matches([AZ?])){
// ...
}
如果你有一个字符,你首先需要将它转换为字符串,然后才能使用正则表达式:
if(Character.toString(symbol).matches([AZ?])){
// ...
}
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.)
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?]")) {
// ...
}
这篇关于比较Java中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!