Java String Leading Character addLeadingSpace(String s, int len)

Here you can find the source of addLeadingSpace(String s, int len)

Description

Adds leading spaces to the given String to the specified length.

License

Open Source License

Parameter

Parameter Description
s The source string.
len The length of the target string.

Return

The String after adding leading spaces.

Declaration

public static String addLeadingSpace(String s, int len) 

Method Source Code

//package com.java2s;

public class Main {
    /**// w w  w .ja  v a  2 s .  c  om
     * Adds leading spaces to the given String to the specified length. Nothing
     * will be done if the length of the given String is equal to or greater
     * than the specified length.
     * 
     * @param s
     *            The source string.
     * @param len
     *            The length of the target string.
     * @return The String after adding leading spaces.
     */
    public static String addLeadingSpace(String s, int len) {
        return addLeadingCharacter(s, ' ', len);
    }

    /**
     * Adds specified leading characters to the specified length. Nothing will
     * be done if the length of the given String is equal to or greater than the
     * specified length.
     * 
     * @param s
     *            The source string.
     * @param c
     *            The leading character(s) to be added.
     * @param len
     *            The length of the target string.
     * @return The String after adding the specified leading character(s).
     */
    public static String addLeadingCharacter(String s, char c, int len) {
        if (s != null) {
            StringBuffer sb = new StringBuffer();
            int count = len - s.length();
            for (int i = 0; i < count; i++) {
                sb.append(c);
            }
            sb.append(s);
            return sb.toString();
        } else {
            return null;
        }
    }

    /**
     * Converts object to a string.<br>
     * If object is null then return null
     * 
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
        if (null == obj) {
            return null;
        } else {
            return obj.toString();
        }
    }
}

Related

  1. addLeadingSlash(String fileName)
  2. addLeadingSlash(String path)
  3. addLeadingSlash(String path)
  4. addLeadingSlash(String string)
  5. addLeadingSpace(String s, int len)
  6. addLeadingUnixSlash(String fileName)
  7. addLeadingZero(byte[] value)
  8. addLeadingZero(final int value)
  9. addLeadingZero(String aString, int aAmountOfZeros)