Trim all occurences of the supplied leading character from the given String. - Java java.lang

Java examples for java.lang:String Strip

Description

Trim all occurences of the supplied leading character from the given String.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        char leadingCharacter = 'a';
        System.out.println(trimLeadingCharacter(str, leadingCharacter));
    }//from   w w w.  j av  a 2 s .  c o  m

    /**
     * Trim all occurences of the supplied leading character from the given String.
     *
     * @param str
     *            the String to check
     * @param leadingCharacter
     *            the leading character to be trimmed
     * @return the trimmed String
     */
    public static String trimLeadingCharacter(final String str,
            final char leadingCharacter) {

        if (!hasLength(str))
            return str;
        final StringBuilder sb = new StringBuilder(str);
        while ((sb.length() > 0) && (sb.charAt(0) == leadingCharacter)) {
            sb.deleteCharAt(0);
        }
        return sb.toString();
    }

    /**
     * Check that the given CharSequence is neither <code>null</code> nor of length 0. Note: Will return
     * <code>true</code> for a CharSequence that purely consists of whitespace. <p><pre>
     * StringUtils.hasLength(null) = false StringUtils.hasLength("") = false StringUtils.hasLength(" ") = true
     * StringUtils.hasLength("Hello") = true </pre>
     *
     * @param str
     *            the CharSequence to check (may be <code>null</code>)
     * @return <code>true</code> if the CharSequence is not null and has length
     * @see #hasText(String)
     */
    public static boolean hasLength(final CharSequence str) {

        return ((str != null) && (str.length() > 0));
    }

    /**
     * Check that the given String is neither <code>null</code> nor of length 0. Note: Will return
     * <code>true</code> for a String that purely consists of whitespace.
     *
     * @param str
     *            the String to check (may be <code>null</code>)
     * @return <code>true</code> if the String is not null and has length
     * @see #hasLength(CharSequence)
     */
    public static boolean hasLength(final String str) {

        return hasLength((CharSequence) str);
    }
}

Related Tutorials