判斷字符串是否爲整數的方法(轉載)

1.使用類型轉換判斷

   1 try { 
   2              String str="123abc"
   3             int num=Integer.valueOf(str);//把字符串強制轉換爲數字 
   4             return true;//如果是數字,返回True 
   5          } catch (Exception e) { 
   6             return false;//如果拋出異常,返回False 
   7          }

 

2.使用正則表達式判斷

   1 String str = "abc123"
   2 boolean isNum = str.matches("[0-9]+"); 
   3 //+表示1個或多個(如"3"或"225"),*表示0個或多個([0-9]*)(如""或"1"或"22"),?表示0個或1個([0-9]?)(如""或"7")

 

 

3.使用Pattern類和Matcher

   1      String str = "123"
   2          Pattern pattern = Pattern.compile("[0-9]+"); 
   3          Matcher matcher = pattern.matcher((CharSequence) str); 
   4         boolean result = matcher.matches(); 
   5         if (result) { 
   6              System.out.println("true"); 
   7          } else { 
   8              System.out.println("false"); 
   9          }

 

4.使用Character.isDigit(char)判斷

   1 String str = "123abc"
   2   if (!"".equals(str)) { 
   3    char num[] = str.toCharArray();//把字符串轉換爲字符數組 
   4     StringBuffer title = new StringBuffer();//使用StringBuffer類,把非數字放到title中 
   5     StringBuffer hire = new StringBuffer();//把數字放到hire中 
   6 
   7    for (int i = 0; i < num.length; i++) { 
   8 
   9   // 判斷輸入的數字是否爲數字還是字符 
10     if (Character.isDigit(num[i])) {把字符串轉換爲字符,再調用Character.isDigit(char)方法判斷是否是數字,是返回True,否則False 
11          hire.append(num[i]);// 如果輸入的是數字,把它賦給hire 
12      } else { 
13       title.append(num[i]);// 如果輸入的是字符,把它賦給title 
14      } 
15     } 
16    }

 

發佈了19 篇原創文章 · 獲贊 17 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章