判断字符串是不是数字,大家可能会用一些java自带的方法,也有可能用其他怪异的招式,比如判断是不是整型数字,将字符串强制转换成整型,不是数字的就会抛出错误,那么就不是整型的了。
1。java类库自带的方法:
isDigit 只能作用于char,所以判断字符串是否为数字,要一个一个拿出char进行判断
public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
2。用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
这两个包,接下来是代码
public boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
3.还是正则表达式
public static boolean isNumeric(String str){
if(str.matches("\\d*"){
return true;
}else{
return false;
}
}
4.用ascii码
public static boolean isNumeric(String str){
for(int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false;
}
return true;
} 5、 string str="123";
int val;
if(int.TryParse(str,out val))
{
//是int数字
}
else
{
// 不是数字
} 6、 string input1 = "1231.23"; string input2 = "123123"; bool isDecimal = Regex.IsMatch(input1, @"^[-]?\d+[.]?\d*$"); bool isNunber = Regex.IsMatch(input2, @"^[-]?[0-9]*$");
7、速度最快
public static bool IsNum(String str)
{
for(int i=0;i<str.Length;i++)
{
if(!Char.IsNumber(str,i))
return false;
}
return true;
}
或用正则表达式:"^\d+$"
还可以用Int32.Parse()抛出的Exception来判断:
try
{
Int32.Parse(toBeTested);
}
catch
{
//发生了异常,那么就不是数字了。
}