`
ordinary
  • 浏览: 76935 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

检查字符串是否是整数

    博客分类:
  • java
阅读更多
检查字符串是否是整数
   今天在论坛中看见一个贴,讨论用异常检验字符串是否为整数,出处http://www.iteye.com/topic/856221。个人总结了里面的方法。有如下四种:
1、 异常检测法;2、每个字符检测法;3、使用Character中的isDigit法;4、正则表达式法。个人分析比较了下这四种方法。如有错误请指出;
1、 异常检测法
代码如下:
public static boolean validateInteger1(String str) { 
try { 
        Integer.parseInt(str); 
     } catch (Exception ex) { 
         return false; 
     } 
     return true; 

这代码看起来简洁,容易理解,下面仔细分析下parseInt方法:
    public static int parseInt(String s, int radix)
throws NumberFormatException
    {
        if (s == null) {
            throw new NumberFormatException("null");
        }

if (radix < Character.MIN_RADIX) {
    throw new NumberFormatException("radix " + radix +
    " less than Character.MIN_RADIX");
}

if (radix > Character.MAX_RADIX) {
    throw new NumberFormatException("radix " + radix +
    " greater than Character.MAX_RADIX");
}

int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;

if (max > 0) {
    if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
    } else {
limit = -Integer.MAX_VALUE;
    }
    multmin = limit / radix;
    if (i < max) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
    throw NumberFormatException.forInputString(s);
} else {
    result = -digit;
}
    }
    while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
    throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
    throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
    throw NumberFormatException.forInputString(s);
}
result -= digit;
    }
} else {
    throw NumberFormatException.forInputString(s);
}
if (negative) {
    if (i > 1) {
return result;
    } else { /* Only got "-" */
throw NumberFormatException.forInputString(s);
    }
} else {
    return -result;
}
}
   花性能主要在1、异常中,2、   针对每个字符进行while循环中。
2、 每个字符检测法;
代码如下:
    public static boolean validateInteger2(String str) { 
        char[] chars = str.toCharArray(); 
        for (int i = 0; i < chars.length; i++) { 
            if ((chars[i] > '9' || chars[i] < '0') && !(i == 0 && chars[0] == '-' && chars.length > 1)) { 
                return false; 
            } 
        } 
        return chars.length > 0; 

这种方法就是检测是否满足数字。
3、使用Character中的isDigit法
public static boolean validateInteger3(String str) { 
if (str == null) { 
          return false; 
      } 
        int sz = str.length(); 
       for (int i = 0; i < sz; i++) { 
           if (Character.isDigit(str.charAt(i)) == false) { 
               return false; 
         } 
       } 
      return true; 
   } 
方法3和方法2基本相同,也是遍历每个字符,唯一的区别就是检测字符是否满足数字的条件让我们看看isDigit
    public static boolean isDigit(int codePoint) {
        boolean bDigit = false;

        if (codePoint >= MIN_CODE_POINT && codePoint <= FAST_PATH_MAX) {
            bDigit = CharacterDataLatin1.isDigit(codePoint);
        } else {
            int plane = getPlane(codePoint);
            switch(plane) {
            case(0):
                bDigit = CharacterData00.isDigit(codePoint);
                break;
            case(1):
                bDigit = CharacterData01.isDigit(codePoint);
                break;
            case(2):
                bDigit = CharacterData02.isDigit(codePoint);
                break;
            case(3): // Undefined
            case(4): // Undefined
            case(5): // Undefined
            case(6): // Undefined
            case(7): // Undefined
            case(8): // Undefined
            case(9): // Undefined
            case(10): // Undefined
            case(11): // Undefined
            case(12): // Undefined
            case(13): // Undefined
                bDigit = CharacterDataUndefined.isDigit(codePoint);
                break;
            case(14):
                bDigit = CharacterData0E.isDigit(codePoint);
                break;
            case(15): // Private Use
            case(16): // Private Use
                bDigit = CharacterDataPrivateUse.isDigit(codePoint);
                break;
            default:
                // the argument's plane is invalid, and thus is an invalid codepoint
                // bDigit remains false;
                break;                         
            }
        }
        return bDigit;
}
该方法是通过case的方法进行批判,这样匹配的效率比方法2中的比较要高一些,但测试结果却不如人意,当字符串全为数字并字符长度比较长时,方法2比方法3效率高。
4、正则表达式法
    public static boolean validateInteger4(String str){
    String reg="^(-?)[1-9]+\\d*|0"; 
   boolean tem=false; 
         Pattern pattern = Pattern.compile(reg); 
         Matcher matcher=pattern.matcher(str); 
         tem=matcher.matches(); 
         return tem; 
}
正则表达式就不多讲了。
下面把四种方法进行比较:
代码如下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class Test {
    private static final int TIMES = 1000000;
    /**
     * 单字符时,把long设置为1
     * 当多字符时,把Long设置为100
     */
    private static final int LONG = 10000; 
public static void main(String[] args) {
StringBuffer str= new StringBuffer();
for(int i=1;i<LONG;i++){
str.append("1");//当是数字的时候设置为1当是字母时设置为a
}
Long startTime=System.nanoTime();

for(int i=1;i<TIMES;i++){
validateInteger1(str.toString());
}
System.out.println(System.nanoTime()-startTime);
}
public static boolean validateInteger1(String str) { 
try { 
        Integer.parseInt(str); 
     } catch (Exception ex) { 
         return false; 
     } 
     return true; 


    public static boolean validateInteger2(String str) { 
        char[] chars = str.toCharArray(); 
        for (int i = 0; i < chars.length; i++) { 
            if ((chars[i] > '9' || chars[i] < '0') && !(i == 0 && chars[0] == '-' && chars.length > 1)) { 
                return false; 
            } 
        } 
        return chars.length > 0; 
    } 
    public static boolean validateInteger3(String str) { 
        if (str == null) { 
            return false; 
        } 
        int sz = str.length(); 
        for (int i = 0; i < sz; i++) { 
            if (Character.isDigit(str.charAt(i)) == false) { 
                return false; 
            } 
        } 
        return true; 
    } 
   
    public static boolean validateInteger4(String str){
    String reg="^(-?)[1-9]+\\d*|0"; 
    boolean tem=false; 
         Pattern pattern = Pattern.compile(reg); 
         Matcher matcher=pattern.matcher(str); 
         tem=matcher.matches(); 
         return tem; 
    }
}
测试结果如下:
方法 检查单字符串整数时间 检查多字符串整数时间 检查单字符串非整数时间 检查多字符串非整数时间
异常检测法 2175653571 3096202439 2120862098 2865671699
每个字符检测法 97425542 583244799 43266996 292156840
使用common-lang中的StringUtils法 78209925 1509344837 19438843 184180683
正则表达式法 1862483011 5208720638 1858216885 2075793713

通过测试发现方法3在性能和简洁性上都比较好,因此建议检测字符串是否为整数时,使用方法3。如果谁有更好的方法,请告诉我。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics