Java String Pad Left lpad(String s, int width)

Here you can find the source of lpad(String s, int width)

Description

Left pad string with blanks to specified width.

License

Open Source License

Parameter

Parameter Description
s The string to pad.
width The width to pad to.

Return

"s" padded with enough blanks on left to be "width" columns wide.

Declaration


public static String lpad(String s, int width) 

Method Source Code

//package com.java2s;
/*   Please see the license information at the end of this file. */

public class Main {
    /**   Left pad string with blanks to specified width.
     */*from  w w w .ja  v a2s .  com*/
     *   @param   s      The string to pad.
     *   @param   width   The width to pad to.
     *
     *   @return         "s" padded with enough blanks on left
     *               to be "width" columns wide.
     */

    public static String lpad(String s, int width) {
        if (s.length() < width) {
            return dupl(' ', width - s.length()) + s;
        } else {
            return s;
        }
    }

    /** Duplicate character into string.
     *
     *   @param   ch      The character to be duplicated.
     *   @param   n      The number of duplicates desired.
     *
     *   @return         String containing "n" copies of "ch".
     *
     *   <p>
     *   if n <= 0, the empty string "" is returned.
     *   </p>
     */

    public static String dupl(char ch, int n) {
        if (n > 0) {
            StringBuffer result = new StringBuffer(n);

            for (int i = 0; i < n; i++) {
                result.append(ch);
            }

            return result.toString();
        } else {
            return "";
        }
    }

    /** Duplicate string into string.
     *
     *   @param   s      The string to be duplicated.
     *   @param   n      The number of duplicates desired.
     *
     *   @return         String containing "n" copies of "s".
     *
     *   <p>
     *   if n <= 0, the empty string "" is returned.
     *   </p>
     */

    public static String dupl(String s, int n) {
        if (n > 0) {
            StringBuffer result = new StringBuffer(n);

            for (int i = 0; i < n; i++) {
                result.append(s);
            }

            return result.toString();
        } else {
            return "";
        }
    }
}

Related

  1. lPad(String input, String replace, int length)
  2. lpad(String s, char addChar, int length)
  3. lpad(String s, int len, char ch)
  4. lpad(String s, int len, String padc)
  5. lpad(String s, int length, char pad)
  6. lpad(String s, String fill, int len)
  7. lpad(String src, int length, char padding)
  8. lpad(String str, char pad, int len)
  9. lPad(String str, int len, char pad)