Trims all instances of a string from the end of the passed StringBuilder. - Java java.lang

Java examples for java.lang:String Trim

Description

Trims all instances of a string from the end of the passed StringBuilder.

Demo Code


//package com.java2s;

public class Main {

    /**//from   w  w w .  j a  va 2s  . co  m
     * Trims all instances of <code>trimChar</code> from the end of the passed StringBuilder.
     * @param buff The StringBuilder to trim
     * @param trimChar The string to trim off the end of the buffer
     * @return the modified buffer
     */
    public static StringBuilder trimCharacters(final StringBuilder buff,
            String trimChar) {
        if (buff == null)
            return new StringBuilder("");
        if (trimChar == null)
            trimChar = " ";
        int trimCharLength = trimChar.length();
        if (buff.length() >= trimCharLength) {
            int start = buff.length() - (trimCharLength);
            int end = buff.length();
            while (buff.substring(start, end).equals(trimChar)) {
                buff.delete(start, end);
                start = buff.length() - (trimCharLength);
                end = buff.length();
            }
        }
        return buff;
    }
}

Related Tutorials