Java中怎樣判斷一個字串是否是數字
在程式設計的時候,經常遇到要判斷一個字串中的字元是否是數字(0-9),判斷字串是不是數字,大家可能會用一些java自帶的方法,也有可能用其他怪異的招式,比如判斷是不是整型數字,將字串強制轉換成整型,不是數字的就會丟擲錯誤,那麼就不是整型的了,下面我給大家介紹幾種實現方法
1.使用Character.isDigit(char)判斷(僅能判斷一個字元
String str = "123abc";
if (!"".equals(str)) {
char num[] = str.toCharArray();//把字串轉換為字元陣列
StringBuffer title = new StringBuffer();//使用StringBuffer類,把非數字放到title中
StringBuffer hire = new StringBuffer();//把數字放到hire中
for (int i = 0; i < num.length; i++) {
// 判斷輸入的數字是否為數字還是字元
if (Character.isDigit(num[i])) {把字串轉換為字元,再呼叫Character.isDigit(char)方法判斷是否是數字,是返回True,否則False
hire.append(num[i]);// 如果輸入的是數字,把它賦給hire
} else {
title.append(num[i]);// 如果輸入的是字元,把它賦給title
}
}
}
2.使用型別轉換判斷
try {
String str="123abc";
int num=Integer.valueOf(str);//把字串強制轉換為數字
return true;//如果是數字,返回True
} catch (Exception e) { return false;//如果丟擲異常,返回False }
3.使用正則表示式判斷
String str = "";
boolean isNum = str.matches("[0-9]+");
//+表示1個或多個(如"3"或"225"),*表示0個或多個([0-9]*)(如""或"1"或"22"),?表示0個或1個([0-9]?)(如""或"7")
4.使用Pattern類和Matcher
String str = "123";
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher((CharSequence) str);
boolean result = matcher.matches();
if (result) {
System.out.println("true");
} else {
System.out.println("false");
}