Java String Leading Character addLeadingCharacter(String s, char c, int len)

Here you can find the source of addLeadingCharacter(String s, char c, int len)

Description

Adds specified leading characters to the specified length.

License

Open Source License

Parameter

Parameter Description
s The source string.
c The leading character(s) to be added.
len The length of the target string.

Return

The String after adding the specified leading character(s).

Declaration

public static String addLeadingCharacter(String s, char c, int len) 

Method Source Code

//package com.java2s;

public class Main {
    /**// ww w.j  a  v a2 s  .  c o m
     * 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. addLeadingCharacter(String s, char c, int len)
  2. addLeadingSlash(String fileName)
  3. addLeadingSlash(String fileName)
  4. addLeadingSlash(String path)
  5. addLeadingSlash(String path)