Java removes spaces on the right using the String. trim () function

Source: Internet
Author: User

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 thisStringObject represents an empty character sequence, or the first and last characters of character sequence represented by thisStringObject both have codes greater'\u0020'(The space character), then a reference to thisStringObject is returned.

    Otherwise, if there is no character with a code greater'\u0020'In the string, then a newStringObject 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 newStringObject 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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.