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