Java String remove white spaces from left

Description

Java String remove white spaces from left


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "   demo2s.com   ";
        System.out.println(">"+lstrip(str)+"<");
    }//from w w w. ja  v  a  2s  .  c o  m

    public static final String WHITE_SPACES = " \r\n\t\u3000\u00A0\u2007\u202F";

    /** lstrip - strips spaces from left
     * @param str what to strip
     * @return String the striped string
     */
    public static String lstrip(String str) {
        return megastrip(str, true, false, WHITE_SPACES);
    }

    /**
     * This is a both way strip
     *
     * @param str the string to strip
     * @param left strip from left
     * @param right strip from right
     * @param what character(s) to strip
     * @return the stripped string
     */
    public static String megastrip(String str, boolean left, boolean right, String what) {
        if (str == null) {
            return null;
        }

        int limitLeft = 0;
        int limitRight = str.length() - 1;

        while (left && limitLeft <= limitRight && what.indexOf(str.charAt(limitLeft)) >= 0) {
            limitLeft++;
        }
        while (right && limitRight >= limitLeft && what.indexOf(str.charAt(limitRight)) >= 0) {
            limitRight--;
        }

        return str.substring(limitLeft, limitRight + 1);
    }
}



PreviousNext

Related