Java String Chop chopTrailingChars(String source, char[] chars)

Here you can find the source of chopTrailingChars(String source, char[] chars)

Description

chop Trailing Chars

License

Apache License

Parameter

Parameter Description
source Source string
chars Symbols to be trimmed

Return

string without all specified chars at the end. For example, chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\'}) is "c:\\my_directory\\//", chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\','/'}) is "c:\my_directory". Actually this method can be used to normalize file names to chop trailing separator chars.

Declaration

public static String chopTrailingChars(String source, char[] chars) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w .j av a2  s .  c  om*/
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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 {
    /**
     * @param source Source string
     * @param chars  Symbols to be trimmed
     * @return string without all specified chars at the end. For example,
     *         <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\'}) is <code>"c:\\my_directory\\//"</code>,
     *         <code>chopTrailingChars("c:\\my_directory\\//\\",new char[]{'\\','/'}) is <code>"c:\my_directory"</code>.
     *         Actually this method can be used to normalize file names to chop trailing separator chars.
     */
    public static String chopTrailingChars(String source, char[] chars) {
        StringBuffer sb = new StringBuffer(source);
        while (true) {
            boolean atLeastOneCharWasChopped = false;
            for (int i = 0; i < chars.length && sb.length() > 0; i++) {
                if (sb.charAt(sb.length() - 1) == chars[i]) {
                    sb.deleteCharAt(sb.length() - 1);
                    atLeastOneCharWasChopped = true;
                }
            }
            if (!atLeastOneCharWasChopped) {
                break;
            }
        }
        return sb.toString();
    }
}

Related

  1. chopScheme(String path)
  2. chopString(String argString, int argLength)
  3. chopString(String str, int len)
  4. chopString(String title, int maxLen)
  5. chopToNSignificantDigits(final float original, int no_of_sig_digits)