Java中判斷字串是否為數位五種方法

來源:互聯網
上載者:User

標籤:

推薦使用第二個方法,速度最快。

方法一:用JAVA內建的函數

Java代碼  
  1. public static boolean isNumeric(String str){   
  2.   for (int i = str.length();--i>=0;){     
  3.    if (!Character.isDigit(str.charAt(i))){   
  4.     return false;   
  5.    }   
  6.   }   
  7.   return true;   
  8. }  
public static boolean isNumeric(String str){  for (int i = str.length();--i>=0;){     if (!Character.isDigit(str.charAt(i))){    return false;   }  }  return true;}



方法二:

Java代碼  
  1. /*  
  2.   * 判斷是否為整數   
  3.   * @param str 傳入的字串   
  4.   * @return 是整數返回true,否則返回false   
  5. */  
  6.   
  7.   
  8.   public static boolean isInteger(String str) {     
  9.     Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");     
  10.     return pattern.matcher(str).matches();     
  11.   }  
/*  * 判斷是否為整數   * @param str 傳入的字串   * @return 是整數返回true,否則返回false */  public static boolean isInteger(String str) {      Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");      return pattern.matcher(str).matches();    }



方法三:

Java代碼  
  1. public static boolean isNumeric(String str){   
  2.     Pattern pattern = Pattern.compile("[0-9]*");   
  3.     return pattern.matcher(str).matches();      
  4. }  
public static boolean isNumeric(String str){    Pattern pattern = Pattern.compile("[0-9]*");    return pattern.matcher(str).matches();   }



方法四:

Java代碼  
  1. public final static boolean isNumeric(String s) {   
  2.         if (s != null && !"".equals(s.trim()))   
  3.             return s.matches("^[0-9]*$");   
  4.         else  
  5.             return false;   
  6.     }  
public final static boolean isNumeric(String s) {if (s != null && !"".equals(s.trim()))return s.matches("^[0-9]*$");elsereturn false;}



3方法五:用ascii碼

Java代碼  
  1. public static boolean isNumeric(String str){   
  2.    for(int i=str.length();--i>=0;){   
  3.       int chr=str.charAt(i);   
  4.       if(chr<48 || chr>57)   
  5.          return false;   
  6.    }   
  7.    return true;   
  8. }   
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;} 



文章地址:
http://javapub.iteye.com/blog/666544

 

Java中判斷字串是否為數位五種方法 (轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.