Java String Pad Left lpad(final String s, final String pad, final int size)

Here you can find the source of lpad(final String s, final String pad, final int size)

Description

add characters on the left until the string get as long as the specified size

License

Open Source License

Parameter

Parameter Description
s a parameter
size a parameter
pad a parameter

Declaration

public static String lpad(final String s, final String pad, final int size) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**// w ww.  j a v a 2 s. co  m
     * add characters on the left until the string get as long as the specified size
     *
     * @param s
     * @param size
     * @param pad
     * @return
     */
    public static String lpad(final String s, final String pad, final int size) {
        int missing = size - s.length();
        StringBuffer sb = new StringBuffer();
        if (missing > 0) {
            int len = sb.length();
            while (len < missing) {
                String ppad = cut(pad, missing - len);
                sb.append(ppad);
                missing -= ppad.length();
            }
        }
        return sb + s;
    }

    /**
     * Cut the given string so it may be at maximum 'size' characters long
     *
     * @param s
     *            string to cut
     * @param size
     *            amount of characters to keep
     * @return
     */
    public static String cut(final String s, final int size) {
        if (s.length() < size) {
            return s;
        } else if (size < 0) {
            return "";
        }
        return s.substring(0, size);
    }

    /**
     * a 'safe' @link {@link String#substring(int, int)} that does not throw exceptions when indexes are false.
     *
     * @param s
     *            any string
     * @param startIndex
     *            start index (maybe greater that endIndex)
     * @param endIndex
     *            required end index (may greater that the string itself)
     * @return substring
     */
    public static String substring(final String s, int startIndex, int endIndex) {
        startIndex = Math.min(s.length(), Math.max(0, startIndex));
        endIndex = Math.min(s.length(), Math.max(0, endIndex));
        return s.substring(Math.min(startIndex, endIndex), Math.max(startIndex, endIndex));
    }
}

Related

  1. leftPadWithZeros(String input, int expectedSize)
  2. leftPadZeros(int value, int digits, StringBuilder sb)
  3. leftZeroPad(String s)
  4. leftZeroPadding(int number, int howManyChar)
  5. lpad(final String input, final String padCode, final int toLength)
  6. lpad(int i, int length, char c)
  7. lpad(int length, long number)
  8. lpad(int maxDigits, long val)
  9. lpad(int value, int padLen, char padChar)