What's the best way to check if a String represents an integer in Java?

后端 未结 30 1443
野趣味
野趣味 2020-11-22 05:45

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.         


        
30条回答
  •  感情败类
    2020-11-22 06:28

    I do not like method with regex, because regex can not check ranges (Integer.MIN_VALUE, Integer.MAX_VALUE).

    If you expect int value in most cases, and not int is something uncommon, then I suggest version with Integer.valueOf or Integer.parseInt with NumberFormatException catching. Advantage of this approach - your code has good readability:

    public static boolean isInt(String s) {
      try {
        Integer.parseInt(s);
        return true;
      } catch (NumberFormatException nfe) {
        return false;
      }
    }
    

    If you need to check if String is integer, and care about perfomance then the best way will be to use java jdk implementation of Integer.parseInt, but little modified (replacing throw with return false):

    This function has good perfomence and garantee right result:

       public static boolean isInt(String s) {
        int radix = 10;
    
        if (s == null) {
            return false;
        }
    
        if (radix < Character.MIN_RADIX) {
            return false;
        }
    
        if (radix > Character.MAX_RADIX) {
            return false;
        }
    
        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
    
        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    return false;
    
                if (len == 1) // Cannot have lone "+" or "-"
                    return false;
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0) {
                    return false;
                }
                if (result < multmin) {
                    return false;
                }
                result *= radix;
                if (result < limit + digit) {
                    return false;
                }
                result -= digit;
            }
        } else {
            return false;
        }
        return true;
    }
    

提交回复
热议问题