检查String是否表示Java中的整数的最佳方法是什么?
我通常使用以下习惯来检查字符串是否可以转换为整数。
I normally use the following idiom to check if a String can be converted to an integer.
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
这只是我,还是看起来有点像hackish的?什么是更好的方式?
Is it just me, or does this seem a bit hackish? What's a better way?
查看我的答案(基准测试,基于早期回答,请 CodingWithSpike )了解我的原因扭转了我的立场并接受了 Jonas Klemming对此问题的回答。我认为这个原始代码将被大多数人使用,因为它实现起来更快,更易于维护,但是当提供非整数数据时它会慢一个数量级。
See my answer (with benchmarks, based on the earlier answer by CodingWithSpike) to see why I've reversed my position and accepted Jonas Klemming's answer to this problem. I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
如果您不关心潜在的溢出问题,此函数的执行速度比使用 Integer.parseInt()
快20-30倍。
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using Integer.parseInt()
.
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
if (str.isEmpty()) {
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;
}