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中的整数的最佳方法是什么?


- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01