问题
使用 StringUtils.isNumeric 判断是否是数字字符串
public static void main(String[] args) { System.out.println(StringUtils.isNumeric("")); }
竟然输出
true
解决过程
看了下源码得知 StringUtils.isNumeric("") = true 确实会输出 true
注意此时我用的是 org.apache.commons.lang 这个版本的包
/**
* <p>Checks if the String contains only unicode digits.
* A decimal point is not a unicode digit and returns false.</p>
*
* <p><code>null</code> will return <code>false</code>.
* An empty String (length()=0) will return <code>true</code>.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if only contains digits, and is non-null
*/
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
我在做了一次测试
输出
false
我用的这个版本 org.apache.commons.lang3 包,我们看下源码
public static boolean isNumeric(CharSequence cs) {
if (isEmpty(cs)) {
return false;
} else {
int sz = cs.length();
for(int i = 0; i < sz; ++i) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
所以 org.apache.commons.lang3 版本已经把问题修复!
总结
建议使用 StringUtils.isNumeric 方法,导入 org.apache.commons.lang3 版本包。
来源:oschina
链接:https://my.oschina.net/hp2017/blog/4948447