原文网址:Java之String系列--判断字符串是否为数字_IT利刃出鞘的博客-CSDN博客
简介
本文介绍Java判断字符串是否为数字的方法。
法1:单个字符判断
public static boolean checkIsNumeric(String str) {
String tmpStr = str;
// 判断负数
if (str.startsWith("-")) {
tmpStr = str.substring(1);
}
for (int i = tmpStr.length(); --i >= 0; ) {
if (!Character.isDigit(tmpStr.charAt(i))) {
return false;
}
}
return true;
}
法2:正则表达式
// import java.util.regex.Pattern;
public static boolean checkIsNumeric(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
法3:整数的parse方法
public static boolean checkIsNumeric(String str) {
try {
Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
法4:Ascii码
public static boolean checkIsNumeric(String str) {
String tmpStr = str;
// 判断负数
if (str.startsWith("-")) {
tmpStr = str.substring(1);
}
for (int i = tmpStr.length(); --i >= 0; ) {
int chr = tmpStr.charAt(i);
if (chr < 48 || chr > 57)
return false;
}
return true;
}