The trim function has two special points. 1. It can remove spaces at both ends of the string! That is, after "ABCD" is processed, it is "ABCD. 2. It not only removes "", but also '\ t',' \ n' and other characters. The function description is as follows:
- Returns a copy of the string, with leading and trailing whitespace omitted.
If thisString
Object represents an empty character sequence, or the first and last characters of character sequence represented by thisString
Object both have codes greater'\u0020'
(The space character), then a reference to thisString
Object is returned.
Otherwise, if there is no character with a code greater'\u0020'
In the string, then a newString
Object representing an empty string is created and returned.
Otherwise, letKBe the index of the first character in the string whose code is greater'\u0020'
, And letMBe the index of the last character in the string whose code is greater'\u0020'
. A newString
Object is created, representing the substring of this string that begins with the character at indexKAnd ends with the character at indexM-That is, the resultthis.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. all characters before u \ 0020 are cleared, so \ t should be retained. trim () should be used with caution for \ n ()So how can we remove only the spaces on the right of the string?
public String TrimRight(String sString){String sResult = "";if (sString.startsWith(" ")){sResult = sString.substring(0,sString.indexOf(sString.trim().substring(0, 1))+sString.trim().length());}elsesResult = sString.trim();return sResult;}