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

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 就可以了。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值