問題描述
我通常使用以下成語來檢查字符串是否可以轉換為整數.
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;
}
}
只有我一個人,還是這看起來有點駭人聽聞?有什么更好的方法?
Is it just me, or does this seem a bit hackish? What's a better way?
查看我的答案(帶有基準,基于 早期答案.com/users/28278/codingwithspike">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;
}
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;
}
這篇關于檢查字符串是否代表Java中的整數的最佳方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!