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、运用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教程
以上就是java怎样推断字符串是不是是数字?的细致内容,更多请关注ki4网别的相干文章!