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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值