本文介绍了检查字符串是否代表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中的整数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:30