天天看点

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

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

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

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


}