检查字符串是否表示Java中的整数的最佳方法是什么?我通常使用以下成语来检查字符串是否可以转换为整数。public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}}是因为我吗,还是看上去有点刻薄?有什么更好的方法吗?见我的答案(带有基准,基于较早的答案通过CodingWithSpike)看看为什么我改变了立场,接受了乔纳斯·克梅明的回答解决这个问题。我认为这段原始代码将被大多数人使用,因为它更快实现,更易于维护,但是当提供非整数数据时,它会慢几个数量级。
3 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
Integer.parseInt().
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;}添加回答
举报
0/150
提交
取消
