Verify if String is hexadecimal

后端 未结 7 1080
花落未央
花落未央 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:35

    Here some code for different options and execution time results (JDK 8):

    execution time isHex1: 4540
    execution time isHex2: 420
    execution time isHex3: 7907
    execution time regex: 46827
    

    Test code:

    @Test
    public void testPerformance() {
        int count = 100000000;
        char[] chars = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };
        String regexString = new String(chars);
        Pattern pattern = Pattern.compile("^[0-9a-fA-F]+$");
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            for (char c: chars) {
                isHex1(c);
            }
        }
        System.out.println("execution time isHex1: " + (System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            for (char c: chars) {
                isHex2(c);
            }
        }
        System.out.println("execution time isHex2: " + (System.currentTimeMillis() - start));
        for (int i = 0; i < count; i++) {
            for (char c: chars) {
                isHex3(c);
            }
        }
        System.out.println("execution time isHex3: " + (System.currentTimeMillis() - start));
        for (int i = 0; i < count; i++) {
            Matcher matcher = pattern.matcher(regexString);
            matcher.matches();
        }
        System.out.println("execution time regex: " + (System.currentTimeMillis() - start));
    }
    
    private boolean isHex1(char c) {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    }
    
    private boolean isHex2(char c) {
        switch (c) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case 'a':
            case 'b':
            case 'c':
            case 'd':
            case 'e':
            case 'f':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
                return true;
            default:
                return false;
        }
    }
    
    private boolean isHex3(char c) {
        return (Character.digit(c, 16) != -1);
    }
    
    0 讨论(0)
提交回复
热议问题