首页 > 编程语言 > 详细

java判断字符串是否可以转为数字

时间:2015-01-01 14:50:23      阅读:459      评论:0      收藏:0      [点我收藏+]

java运算中,常涉及将String 型的字符串转为int 型数字的情况。

哪些字符串可以转为数字,哪些不可以呢,不能总以Integer.parseInt() 是否抛出异常来判断。

刚好碰到了转换情况,就总结了下,分享出来。


定义方法签名

/**
* 查看一个字符串是否可以转换为数字
* @param str 字符串
* @return true 可以; false 不可以
*/
public static boolean isStr2Num(String str) { 

}

方法体该如何实现呢?两种方式


方法1  Integer.parseInt 转换

		try {
			Integer.parseInt(str);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}

方法2  正则表达式

		
		Pattern pattern = Pattern.compile("^[0-9]*$");
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();


Integer 还有一个静态方法valueOf(String s),查看源码

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

valueOf(String s) 也还是先通过parseInt() 先将字符串转换为数字,然后再转换为Integer对象的

而 parseInt(String s) 返回的是int 型变量,节省了堆内存的开销

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
}

所以,这里的判断使用parseInt 就可以了。


java判断字符串是否可以转为数字

原文:http://blog.csdn.net/magi1201/article/details/42212537

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!