翻譯:郝春利
轉貼請注明出處:http://blog.csdn.net/froole
Java程式開發中經常用到判斷對象字串是否為“空白”的處理。這裡的空白指的不僅僅是""或者null,包括空格、縮緊、改行等,對被看作空白。
通常情況下,我個人比較喜歡使用Apache Jakarta Commons Lang包中的StringUtils#isBlank方法,但是,隻支援英文,如果是全角空格就不好用了。
以下代碼是相容了全角空格的isBlank方法。在判斷是否為半角空白進行中,直接使用JVM的Character#isWhitespace方法,全角的判斷單列出來。
如下:
public static boolean isBlank(CharSequence str){
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isWhitespace(char ch){
if(ch == ' '){
return true;
}
if(Character.isWhitespace(ch)){
return true;
}
return false;
}
<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>
轉貼請注明出處:http://blog.csdn.net/froole