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(' ')。

posted @ 2016-11-14 20:12  Jakey_Hong  阅读(5299)  评论(0编辑  收藏  举报