`

Java中判断字符串是否为数字的五种方法

阅读更多
推荐使用第二个方法,速度最快。

方法一:用JAVA自带的函数
public static boolean isNumeric(String str){
  for (int i = str.length();--i>=0;){  
   if (!Character.isDigit(str.charAt(i))){
    return false;
   }
  }
  return true;
}


方法二:
/*
  * 判断是否为整数 
  * @param str 传入的字符串 
  * @return 是整数返回true,否则返回false 
*/


  public static boolean isInteger(String str) {  
    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
    return pattern.matcher(str).matches();  
  }


方法三:
public static boolean isNumeric(String str){
    Pattern pattern = Pattern.compile("[0-9]*");
    return pattern.matcher(str).matches();   
}


方法四:
public final static boolean isNumeric(String s) {
		if (s != null && !"".equals(s.trim()))
			return s.matches("^[0-9]*$");
		else
			return false;
	}


3方法五:用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;
} 


文章地址:
http://javapub.iteye.com/blog/666544

相关文章:
Java判断是否为整数和浮点数 http://javapub.iteye.com/blog/737689
分享到:
评论
7 楼 houyutao 2018-03-16  
二三四都是错的空字符串也被匹配,*应该改成+
6 楼 kxn308 2016-02-26  
一振风 写道
方法二没有错


一楼说的是对的,方法二是错的好吗,单独的加减号也是匹配的 
5 楼 一振风 2015-10-11  
方法二没有错
4 楼 一振风 2015-10-11  
方法二中没有错, *是重复0次或更多,已经至少有一个数字了 +是至少有两次数字出现
3 楼 solen 2015-04-30  
用instanceof 来一个个判断

List list = new ArrayList();
list.add("aaa");
list.add(111);
for (Object obj : list) {
if (obj instanceof String) {
System.out.println(obj + " is string");
}
if (obj instanceof Integer) {
System.out.println(obj + " is integer");
}
}
2 楼 2047699523 2015-04-21  
java正则判断字符串是否是由纯数字组成的问题
http://www.zuidaima.com/question/1931119473249280.htm
1 楼 Cwind 2012-12-31  
方法二中的正则表达式有点错误,*应替换为+,数字至少应出现一次

相关推荐

Global site tag (gtag.js) - Google Analytics