Android String Trim trimEnd(String s, String extraChars)

Here you can find the source of trimEnd(String s, String extraChars)

Description

Trim characters from only the end of a string.

License

Apache License

Parameter

Parameter Description
s String to be trimmed
extraChars Characters in addition to whitespace characters that should be trimmed. May be null.

Return

String with whitespace and characters in extraChars removed from the end

Declaration

public static String trimEnd(String s, String extraChars) 

Method Source Code

//package com.java2s;
/**/*from  www. ja  va  2 s  .  c o m*/
 * Copyright (c) 2000, Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Trim characters from only the end of a string.
     * This is a convenience method, it simply calls trimEnd(s, null).
     *
     * @param s String to be trimmed
     * @return String with whitespace characters removed from the end
     */
    public static String trimEnd(String s) {
        return trimEnd(s, null);
    }

    /**
     * Trim characters from only the end of a string.
     * This method will remove all whitespace characters
     * (defined by Character.isWhitespace(char), in addition to the characters
     * provided, from the end of the provided string.
     *
     * @param s String to be trimmed
     * @param extraChars Characters in addition to whitespace characters that
     *                   should be trimmed.  May be null.
     * @return String with whitespace and characters in extraChars removed
     *                   from the end
     */
    public static String trimEnd(String s, String extraChars) {
        int trimCount = 0;
        while (trimCount < s.length()) {
            char ch = s.charAt(s.length() - trimCount - 1);
            if (Character.isWhitespace(ch)
                    || (extraChars != null && extraChars.indexOf(ch) >= 0)) {
                trimCount++;
            } else {
                break;
            }
        }

        if (trimCount == 0) {
            return s;
        }
        return s.substring(0, s.length() - trimCount);
    }
}

Related

  1. trimPrefix(final String text, final String prefix)
  2. trimSpace(String oldString)
  3. rightTrimSize(String s)
  4. trim(String s, char c)
  5. trim(String trimStr, String trimChars)
  6. trimStart(String s, String extraChars)
  7. betterTrim(String input)