Best implementation for an isNumber(string) method

前端 未结 19 2380
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

相关标签:
19条回答
  • 2020-12-15 20:35

    I think It could be faster than previous solutions if you do the following (Java):

    public final static boolean isInteger(String in)
    {
        char c;
        int length = in.length();
        boolean ret = length > 0;
        int i = ret && in.charAt(0) == '-' ? 1 : 0;
        for (; ret && i < length; i++)
        {
            c = in.charAt(i);
            ret = (c >= '0' && c <= '9');
        }
        return ret;
    }
    

    I ran the same code that Asaph ran and the result was:

    This operation took 28 ms.

    A huge difference (against 1691 ms and 2049 ms -on my computer). Take in account that this method does not validate if the string is null, so you should do that previously (including the String trimming)

    0 讨论(0)
提交回复
热议问题