Dan Dan - 3 months ago 13
Java Question

How do I compare strings representation of integers?

I was wondering how I could use an if statement as if they were integers for strings?

/**
*
* @param token
* @return true if parameter is the String representation of an integer
* between 0 and 255 (including 0 and 255), false otherwise.
* Strings "0", "1", "2" .... "254", "255" are valid.
* Padded Strings (such as "00000000153") are also valid
*/


public static boolean isValidElement(String token) {
if (token=> 0 || token <=255)
return true;
return false;
}


This is what I currently have in mind at the moment but obviously it won't work for strings.

Answer

You could use Integer.parseInt(), but it allows a leading +, and that's not allowed according to your javadoc.

You can manually test for leading +, then use Integer.parseInt() like this:

public static boolean isValidElement(String token) {
    if (token == null || token.isEmpty() || token.charAt(0) == '+')
        return false;
    try {
        int num = Integer.parseInt(token);
        return (num >= 0 && num <= 255);
    } catch (@SuppressWarnings("unused") NumberFormatException e) {
        return false;
    }
}

For a high-performance solution that don't rely on parseInt() and exception handling, you can use this much longer implementation:

public static boolean isValidElement(String token) {
    if (token == null || token.isEmpty())
        return false;
    // skip leading zeroes
    int i = 0;
    while (i < token.length() && token.charAt(i) == '0')
        i++;
    // validate remaining
    char ch;
    switch (token.length() - i) {
        case 0:
            return true; // Allow "0"
        case 1:
            ch = token.charAt(i);
            return (ch >= '1' && ch <= '9'); // Allow "1" to "9"
        case 2:
            ch = token.charAt(i);
            if (ch >= '1' && ch <= '9') {
                ch = token.charAt(i + 1);
                return (ch >= '0' && ch <= '9'); // Allow "10" to "99"
            }
            return false;
        case 3:
            ch = token.charAt(i);
            if (ch == '1') {
                ch = token.charAt(i + 1);
                if (ch >= '0' && ch <= '9') {
                    ch = token.charAt(i + 2);
                    return (ch >= '0' && ch <= '9'); // Allow "100" to "199"
                }
            } else if (ch == '2') {
                ch = token.charAt(i + 1);
                if (ch >= '0' && ch <= '4') {
                    ch = token.charAt(i + 2);
                    return (ch >= '0' && ch <= '9'); // Allow "200" to "249"
                } else if (ch == '5') {
                    ch = token.charAt(i + 2);
                    return (ch >= '0' && ch <= '5'); // Allow "250" to "255"
                }
            }
            return false;
        default:
            return false;
    }
}