trim string from Left - Java java.lang

Java examples for java.lang:String Trim

Description

trim string from Left

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sourceString = "java2s.com";
        System.out.println(trimLeft(sourceString));
    }/*from w  w  w  .  j  a va2 s.  c om*/

    public static String trimLeft(String sourceString) {
        String result = "";

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);
            int length = buffer.length();

            while ((length != 0)
                    && (Character.isWhitespace(buffer.charAt(0)))) {
                buffer.deleteCharAt(0);
                length--;
            }

            result = buffer.toString();
        }

        return result;
    }

    public static String trimLeft(String sourceString, char removeChar) {
        String result = "";

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);

            while ((buffer.length() > 0) && buffer.charAt(0) == removeChar) {
                buffer.deleteCharAt(0);
            }
            result = buffer.toString();
        }

        return result;
    }

    public static String trimLeft(String sourceString, String removeChars) {
        String result = "";
        int length = removeChars.length();

        if (!isEmpty(sourceString)) {
            StringBuilder buffer = new StringBuilder(sourceString);
            boolean done = false;

            while ((buffer.length() > 0) && !done) {
                done = true;
                for (int i = 0; i < length; i++) {
                    if (buffer.charAt(0) == removeChars.charAt(i)) {
                        buffer.deleteCharAt(0);
                        done = false;
                        break;
                    }
                }
            }
            result = buffer.toString();
        }

        return result;
    }

    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

Related Tutorials