Java方法trim()小記


  我們一般用trim()方法的主要作用,是為了去除字符串的首尾空格。然而根據我個人的實踐經驗發現,trim()這個方法只能去除部分的空格或空白符,比如半角空格;對於全角空格的話,用trim()並不能去除掉。所以這時候就需要通過正則來解決,去掉字符串首尾空格、空白符、換行符或制表符、換行符等:

public static void main(String[] args){
     String keyword = "    空格符與制表符等      ";
     keyword = keyword.replaceAll("^[ *| *| *|//s*]*", "").replaceAll("[ *| *| *|//s*]*$", "");
     System.out.println("keyword : "+keyword);      
}

  還有一個我網上查找到的資料是這么解釋的:首先將trim()這個方法進行反編譯,得到:

public string Trim()
{    return this.TrimHelper(WhitespaceChars, 2);
}

  TrimHelper這個方法進行反編譯之后得到:

private string TrimHelper(char[] trimChars, int trimType)
{    int num = this.Length - 1;    int startIndex = 0;    if (trimType != 1)
    {
        startIndex = 0;        while (startIndex < this.Length)
        {            int index = 0;            char ch = this[startIndex];
            index = 0;            while (index < trimChars.Length)
            {                if (trimChars[index] == ch)
                {                    break;
                }
                index++;
            }            if (index == trimChars.Length)
            {                break;
            }
            startIndex++;
        }
    }    if (trimType != 0)
    {
        num = this.Length - 1;        while (num >= startIndex)
        {            int num4 = 0;            char ch2 = this[num];
            num4 = 0;            while (num4 < trimChars.Length)
            {                if (trimChars[num4] == ch2)
                {                    break;
                }
                num4++;
            }            if (num4 == trimChars.Length)
            {                break;
            }
            num--;
        }
    }    int length = (num - startIndex) + 1;    if (length == this.Length)
    {        return this;
    }    if (length == 0)
    {        return Empty;
    }    return this.InternalSubString(startIndex, length, false);
}

  TrimHelper有兩個參數:第一個參數trimChars,是要從字符串兩端刪除掉的字符的數組;第二個參數trimType,是標識Trim()的類型。trimType的值有3個:當傳入0時,去除字符串頭部的空白字符;傳入1時,去除字符串尾部的空白字符;傳入其他數值則去掉字符串兩端的空白字符。最后得出總結是:String.Trim()方法會去除字符串兩端,不僅僅是空格字符,它總共能去除25種字符:('/t', '/n', '/v', '/f', '/r', ' ', '/x0085', '/x00a0', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '?', '/u2028', '/u2029', ' ', '?')。

  另外還有兩個方法和trim()類似:去除字符串頭部空白字符的TrimStart()和去除字符串尾部空白字符的TrimEnd()。

  如果想去除字符串兩端的任意字符,可使用Trim的重載方法:String.Trim(Char[]),該方法的源碼是:

public string Trim(params char[] trimChars)
{    if ((trimChars == null) || (trimChars.Length == 0))
    {
        trimChars = WhitespaceChars;
    }    return this.TrimHelper(trimChars, 2);
}

  需要注意的是:空格 != 空白字符,想要刪除空格可以使用Trim(' ')。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM