在編程的時候,經(jīng)常遇到要判斷一個字符串中的字符是否是數(shù)字(0-9),判斷字符串是不是數(shù)字,大家可能會用一些java自帶的方法,也有可能用其他怪異的招式,比如判斷是不是整型數(shù)字,將字符串強制轉(zhuǎn)換成整型,不是數(shù)字的就會拋出錯誤,那么就不是整型的了,下面我給大家介紹幾種實現(xiàn)方法。
java如何判斷字符串是否是數(shù)字?
1、使用Character.isDigit(char)判斷(僅能判斷一個字符)
String str = "123abc"; if (!"".equals(str)) { char num[] = str.toCharArray(); //把字符串轉(zhuǎn)換為字符數(shù)組 StringBuffer title = new StringBuffer(); //使用StringBuffer類,把非數(shù)字放到title中 StringBuffer hire = new StringBuffer(); //把數(shù)字放到hire中 for (int i = 0; i < num.length; i++) { // 判斷輸入的數(shù)字是否為數(shù)字還是字符 if (Character.isDigit(num[i])) { 把字符串轉(zhuǎn)換為字符, 再調(diào)用Character.isDigit(char) 方法判斷是否是數(shù)字, 是返回True, 否則False hire.append(num[i]); // 如果輸入的是數(shù)字,把它賦給hire } else { title.append(num[i]); // 如果輸入的是字符,把它賦給title } } }
2、使用類型轉(zhuǎn)換判斷
try { String str = "123abc"; int num = Integer.valueOf(str); //把字符串強制轉(zhuǎn)換為數(shù)字 return true; //如果是數(shù)字,返回True } catch (Exception e) { return false; //如果拋出異常,返回False }
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"); }
推薦教程:Java教程