Java中如何判断一个字符串是不是一个数字

Java中判断一个字符串是否是一个数字

思路一:从底层二进制入手

使用ascii码:

public static boolean isNumeric(String str){
          
     
   for(int i=str.length();--i>=0;){
          
     
      int chr=str.charAt(i);  
      if(chr<48 || chr>57)  
         return false;  
   }  
   return true;  
}

思路二:使用Java提供的API

用JAVA自带的函数isDigit()方法判断

public static boolean isNumeric(String str){
          
     
  for (int i = str.length();--i>=0;){
          
       
   if (!Character.isDigit(str.charAt(i))){
          
     
    return false;  
   }  
  }  
  return true;  
}

思路三:使用正则表达式

方式一:使用正则表达式^[-+]?[d]*$判断

public static boolean isInteger(String str) {
          
       
    Pattern pattern = Pattern.compile("^[-+]?[d]*$");    
    return pattern.matcher(str).matches();    
  }

方式二:使用正则表达式[0-9]*判断

public static boolean isNumeric(String str){
          
     
    Pattern pattern = Pattern.compile("[0-9]*");  
    return pattern.matcher(str).matches();     
}

方式三:使用正则表达式^[0-9]*$判断

public final static boolean isNumeric(String str) {
          
     
        if (str != null && !"".equals(str.trim()))  
            return str.matches("^[0-9]*$");  
        else  
            return false;  
    }
备注:上述方法的返回值说明,true表示是判断的字符串是数字

经验分享 程序员 微信小程序 职场和发展