Verify if String is hexadecimal

后端 未结 7 1197
花落未央
花落未央 2020-12-03 06:39

I have a String like \"09a\" and I need a method to confirm if the text is hexadecimal. The code I\'ve posted does something similar, it verifies that a string is a decimal

7条回答
  •  无人及你
    2020-12-03 07:17

    There's an overloaded Long.parseLong that accepts a second parameter, specifying the radix:

    Long.parseLong(cadena,16);
    

    As an alternative, you could iterate over the characters in the string and call Character.digit(c,16) on them (if any of them return -1 it's not a valid hexadecimal digit). This is especially useful if the string is too large to fit in a long (as pointed out in the comments, that would cause an exception if the first method is used). Example:

    private static boolean isNumeric(String cadena) {
        if ( cadena.length() == 0 || 
             (cadena.charAt(0) != '-' && Character.digit(cadena.charAt(0), 16) == -1))
            return false;
        if ( cadena.length() == 1 && cadena.charAt(0) == '-' )
            return false;
    
        for ( int i = 1 ; i < cadena.length() ; i++ )
            if ( Character.digit(cadena.charAt(i), 16) == -1 )
                return false;
        return true;
    }
    

    BTW, I'd suggest separating the concerns of "testing for a valid number" and "displaying a message to the user", that's why I simply returned false in the example above instead of notifying the user first.

    Finally, you could simply use a regular expression:

    cadena.matches("-?[0-9a-fA-F]+");
    

提交回复
热议问题