What#39;s the best way to check if a String represents an integer in Java?(检查字符串是否代表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;
}
}
只有我一个人,还是这看起来有点骇人听闻?有什么更好的方法?
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中的整数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查字符串是否代表Java中的整数的最佳方法是什么?


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01