java中判斷字串是否是一個整數(轉載)
阿新 • • 發佈:2019-01-01
1.使用型別轉換判斷
try {
String str="123abc";
int num=Integer.valueOf(str);//把字串強制轉換為數字
return true;//如果是數字,返回True
}
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 }
try {
String str="123abc";
int num=Integer.valueOf(str);//把字串強制轉換為數字
return true;//如果是數字,返回True
}
catch (Exception e) {
return false;//如果丟擲異常,返回False}
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 }
來自: http://hi.baidu.com/frjay/blog/item/71b9500a685ee433b1351da8.html