java中String的trim方法只能去除字符串头尾的半角空格,而我们所做的系统往往是用户输入为中文的系统。因此需要我们重写trim方法。
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
* <p>
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* 执行trim操作(包含全角和半角的空格;)
*
* @param str 字符串
* @return 结果字符串
*/
public static String trim(String str) {
if (isBlank(str)) {//判断字符串是否为空或长度为零或是一段空格,上面有该函数代码
return "";
} else {
str = str.trim();// 去掉半角符号的空格
while (str.startsWith(" ")) {//该空格为全角空格
str = str.substring(1, str.length()).trim();
if (isBlank(str)) {
return "";
}
}
while (str.endsWith(" ")) { // 该空格为全角空格
str = str.substring(0, str.length() - 1).trim();
if (isBlank(str)) {
return "";
}
}
}
return str;
}
您的帮助是我莫大的鼓励!喜欢的话可以扫描左侧二维码随意打赏哈~支付宝微信都可以,欢迎看看我的其他文章~
在这里谢谢已经支持的朋友们,打赏有价,支持与鼓励无价!