LeftPadUtils.java•1.83 kB
package org.example;
public final class LeftPadUtils {
/** The single space used when the pad string is empty. */
private static final String SPACE = " ";
private static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* Left pad a String with another string used as a pad.
*
* @param str string to pad, may be null
* @param size desired padded size
* @param padStr the string to pad with (may be empty)
* @return the padded string, or {@code null} if the input string was null
*/
public static String leftPad(final String str,
final int size,
final String padStr) {
if (str == null) {
return null;
}
String pad = padStr;
if (isEmpty(pad)) {
pad = SPACE;
}
final int padLen = pad.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // no padding necessary
}
if (pads == padLen) {
return pad.concat(str);
}
if (pads < padLen) {
final String pre = pad.substring(0, pads);
return pre.concat(str);
}
final char[] padding = new char[pads];
final char[] padChars = pad.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
final String padded = new String(padding);
return padded.concat(str);
}
// Private constructor prevents instantiation of this utility class
private LeftPadUtils() {
throw new AssertionError("No instances allowed");
}
}