trim java_java String 的trim 方法,并不仅仅是去掉空格

本文详细解读了Java String类的trim()方法,指出其不仅移除空格,还会移除ASCII码小于 的所有字符。通过源码分析,展示了如何根据字符编码判断和操作字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果仔细看java api里面关于String.trim()方法的说明,就会明白trim()方法不是仅仅去掉空格,它去掉的是编码小于等于\u0020的字符,也就是在ASCII码里面十六进制20以前的字符。

46a22a6b5c9f66aa31820004b25bdd33.gif

Java API 写道

trim

public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

(返回字符串的拷贝,前后空格被忽略)

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

(如果字符串为空,或者前后都是编码大于\u0020的字符,返回原有字符串的引用)

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.

(否则,大家知道的...)

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

Returns:

A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

再看源代码就更确定了:

public String trim () {

// 这里的start, end 是新字符串开始和结束的位置

int start = offset, last = offset + count - 1;

int end = last;

// 下面的两个while循环计算start 和 end 的值

while ((start <= end) && (value [start] <= ' ')) start++;

while ((end >= start) && (value [end] <= ' ')) end--;

// 如果值和原有的一样,就直接返回原有的字符串

if (start == offset && end == last) return this;

// 用 start 和 end 返回新的字符串

return new String (start, end - start + 1, value);

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-04-06 16:01

浏览 7013

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值