我知道必须有一种更简单的检查方法,但这就是我现在正在做的事情。
if (g.charAt(0) == 'a' || g.charAt(0) =='b' || g.charAt(0) =='c' ||
g.charAt(0) == 'd' || g.charAt(0) =='e' || g.charAt(0) =='f' ||
g.charAt(0) == 'g' || g.charAt(0) =='h')
答案 0 :(得分:38)
依靠字符排序和a..h is a consecutive range:
char firstChar = g.charAt(0);
if (firstChar >= 'a' && firstChar <= 'h') {
// ..
}
答案 1 :(得分:31)
使用正则表达式。将String的第一个字符剪切为子字符串,并在其上匹配。
if(g.substring(0, 1).matches("[a-h]") {
// logic
}
答案 2 :(得分:7)
赫马斯答案的变体:
if("abcdefgh".contains(g.substring(0,1))) do_something();
或
if("abcdefgh".indexOf(g.charAt(0)) >= 0) do_something();
答案 3 :(得分:4)
另一种方法:
if(Array.asList("abcdefgh".toCharArray()).contains(g.charAt(0)))
{
//Logic
}