Too*_*ink 18 java if-statement char
我知道必须有一个更简单的方法来检查,但这就是我现在正在做的事情.
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')
Run Code Online (Sandbox Code Playgroud)
use*_*740 38
依赖于字符排序,a..h是连续范围:
char firstChar = g.charAt(0);
if (firstChar >= 'a' && firstChar <= 'h') {
// ..
}
Run Code Online (Sandbox Code Playgroud)
Mak*_*oto 31
使用正则表达式.将String的第一个字符剪切为子字符串,并匹配它.
if(g.substring(0, 1).matches("[a-h]") {
// logic
}
Run Code Online (Sandbox Code Playgroud)
关于赫马斯答案的变化:
if("abcdefgh".contains(g.substring(0,1))) do_something();
Run Code Online (Sandbox Code Playgroud)
要么
if("abcdefgh".indexOf(g.charAt(0)) >= 0) do_something();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23503 次 |
| 最近记录: |