jueves, 8 de mayo de 2014

A simple way to determine if a String could be an integer

There are a lot of ways to check if a String could represent an integer value. I will show you two very simple and yet fast methods:

Method 1

    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;
    }


Method 2 (modified version of method 1)

    public static boolean isInteger(String in)
    {
        if (in != null)
        {
            char c;
            int i = 0;
            int l = in.length();
            if (l > 0 && in.charAt(0) == '-')
            {
                i = 1;
            }
            if (l > i)
            {
                for (; i < l; i++)
                {
                    c = in.charAt(i);
                    if (c < '0' || c > '9')
                        return false;
                }
                return true;
            }
        }
        return false;
    }


Method 3 

    static final byte[] b = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public final static boolean isInteger(String in)
    {
        char c;
        int length = in.length();
        int i = 0;
        if (length > 0 && in.charAt(0) == '-')
            i = 1;
        if (i >= length)
        {
            return false;
        }
        for (; i < length; i++)
        {
            c = in.charAt(i);
            if (b[c & 0xff] == 0)
                return false;
        }
        return true;
    }



I hope this information is useful.

PS. Be aware that all of these will say that very large strings (with valid big integers) are true, so if you just try to convert them to Integers, an Exception could be thrown.

No hay comentarios.: