Here you can find the source of leftPad(String s, int minLength)
Parameter | Description |
---|---|
s | the string that will be padded. |
minLength | the length to reach. |
public static String leftPad(String s, int minLength)
//package com.java2s; public class Main { /**/*w w w.java2s . c om*/ * Pads the string at the left with spaces until it reaches the desired * length. If the string is longer than this length, then it returns the * unchanged string. * * @param s the string that will be padded. * @param minLength the length to reach. */ public static String leftPad(String s, int minLength) { return leftPad(s, minLength, ' '); } /** * Pads the string at the left with the specified character until it reaches * the desired length. If the string is longer than this length, then it * returns the unchanged string. * * @param s the string that will be padded. * @param minLength the length to reach. * @param filling the filling pattern. */ public static String leftPad(String s, int minLength, char filling) { int ln = s.length(); if (minLength <= ln) { return s; } StringBuffer res = new StringBuffer(minLength); int dif = minLength - ln; for (int i = 0; i < dif; i++) { res.append(filling); } res.append(s); return res.toString(); } /** * Pads the string at the left with a filling pattern until it reaches the * desired length. If the string is longer than this length, then it returns * the unchanged string. For example: <code>leftPad('ABC', 9, '1234')</code> * returns <code>"123412ABC"</code>. * * @param s the string that will be padded. * @param minLength the length to reach. * @param filling the filling pattern. Must be at least 1 characters long. * Can't be <code>null</code>. */ public static String leftPad(String s, int minLength, String filling) { int ln = s.length(); if (minLength <= ln) { return s; } StringBuffer res = new StringBuffer(minLength); int dif = minLength - ln; int fln = filling.length(); if (fln == 0) { throw new IllegalArgumentException("The \"filling\" argument can't be 0 length string."); } int cnt = dif / fln; for (int i = 0; i < cnt; i++) { res.append(filling); } cnt = dif % fln; for (int i = 0; i < cnt; i++) { res.append(filling.charAt(i)); } res.append(s); return res.toString(); } }