1. 程式人生 > >JAVA 判斷字串是否整數

JAVA 判斷字串是否整數

1. 使用型別轉換判斷

try { 
	String str="123abc"; 
	//把字串強制轉換為數字 
	int num=Integer.valueOf(str);
	//如果是數字,返回True 
	return true;
} catch (Exception e) {
	//如果丟擲異常,返回False 
	return false;
}

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


3. 使用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"); 
}


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

String str = "123abc"; 
if (!"".equals(str)) { 
	//把字串轉換為字元陣列
	char num[] = str.toCharArray(); 
	//使用StringBuffer類,把非數字放到title中
	StringBuffer title = new StringBuffer(); 
	//把數字放到hire中
	StringBuffer hire = new StringBuffer(); 

	for (int i = 0; i < num.length; i++) { 
		// 判斷輸入的數字是否為數字還是字元 
		// 把字串轉換為字元,再呼叫Character.isDigit(char)方法判斷是否是數字
		if (Character.isDigit(num[i])) { 
			hire.append(num[i]);// 如果輸入的是數字,把它賦給hire 
		} else { 
			title.append(num[i]);// 如果輸入的是字元,把它賦給title 
		} 
	} 
}