Here you can find the source of rightPad(String s, int minLength)
Parameter | Description |
---|---|
s | the string that will be padded. |
minLength | the length to reach. |
public static String rightPad(String s, int minLength)
//package com.java2s; public class Main { /**/*from w w w . jav a 2s .c om*/ * Pads the string at the right 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 rightPad(String s, int minLength) { return rightPad(s, minLength, ' '); } /** * Pads the string at the right 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 rightPad(String s, int minLength, char filling) { int ln = s.length(); if (minLength <= ln) { return s; } StringBuffer res = new StringBuffer(minLength); res.append(s); int dif = minLength - ln; for (int i = 0; i < dif; i++) { res.append(filling); } return res.toString(); } /** * Pads the string at the right 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>rightPad('ABC', 9, '1234')</code> * returns <code>"ABC412341"</code>. Note that the filling pattern is * started as if you overlay <code>"123412341"</code> with the left-aligned * <code>"ABC"</code>, so it starts with <code>"4"</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 rightPad(String s, int minLength, String filling) { int ln = s.length(); if (minLength <= ln) { return s; } StringBuffer res = new StringBuffer(minLength); res.append(s); int dif = minLength - ln; int fln = filling.length(); if (fln == 0) { throw new IllegalArgumentException("The \"filling\" argument can't be 0 length string."); } int start = ln % fln; int end = fln - start <= dif ? fln : start + dif; for (int i = start; i < end; i++) { res.append(filling.charAt(i)); } dif -= end - start; 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)); } return res.toString(); } }