String trim方法及trim方法重寫

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;
    }



您的幫助是我莫大的鼓勵!喜歡的話可以掃描左側二維碼隨意打賞哈~支付寶微信都可以,歡迎看看我的其他文章~

在這裏謝謝已經支持的朋友們,打賞有價,支持與鼓勵無價!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章