Java String Pad Left lpadWithCount(String input, String str, int count)

Here you can find the source of lpadWithCount(String input, String str, int count)

Description

lpad With Count

License

Open Source License

Declaration

public static String lpadWithCount(String input, String str, int count) 

Method Source Code

//package com.java2s;

public class Main {
    public static final int RIGHT = 1;
    public static final int LEFT = 2;

    public static String lpadWithCount(String input, String str, int count) {
        return doPadWithCount(input, str, count, LEFT);
    }//from  w  w w.ja  v  a  2s.  c o m

    private static String doPadWithCount(String input, String str,
            int totalCount, int type) {
        StringBuffer sb = new StringBuffer();
        String sInput = "";

        if (input.trim().length() > totalCount) {
            sInput = input.trim().substring(0, 10);
        } else {
            sInput = input.trim();
        }

        int padCount = totalCount - sInput.trim().length();
        if (padCount > 0) {
            if (type == LEFT) {
                for (int i = 0; i < padCount; i++)
                    sb.append(str);
            }
            sb.append(padNull(sInput));
            if (type == RIGHT) {
                for (int i = 0; i < padCount; i++)
                    sb.append(str);
            }
        } else {
            return sInput;
        }
        return sb.toString();
    }

    /**
     * Trim input string.
     * @param sInput Input string.
     * @return       Trim the string if it is not null.
     */
    public static String trim(String sInput) {

        if (sInput != null) {
            return sInput.trim();
        } else {
            return sInput;
        }

    }

    public static String padNull(String input) {
        return (input == null) ? "" : input;
    }
}

Related

  1. lPad(String string, char[] padding, int length)
  2. lPad(String target, String fix, int length)
  3. lPad(String val, int length, String padChar)
  4. lpadding(String s, int n, String padding)
  5. lpadSapce(final String src, final int length)