Adapt the width to your needs with String.format():
int width = 15;
// "What's your size?" Padding asks. "15," Text replies. String padded = String.format("%-" + width + "s", "text"); // "text "
Padding with specific character
Replace the 'space' in padding with any desired character:
// Who needs spaces, when you have stars!String paddedStar = String.format("%-10s", "text").replace(' ', '*'); // "text******"
Padding with Guava library
Marginally less pounds, but more robust with Guava library:
// When 'x' marks the start, and 'y' greets you at the end. String paddedStart = Strings.padStart("text", 10, 'x'); // "xxxxxxtext"String paddedEnd = Strings.padEnd("text", 10, 'y'); // "textyyyyyy"
Advanced Padding Techniques
Concatenation for Padding
Simple concatenation might be your cup of tea:
// When in doubt, simply pad it out! String rightPadded = "text" + " ".repeat(10 - "text".length());
String leftPadded = " ".repeat(10 - "text".length()) + "text";
Enhance your Numeric Padding
Take DecimalFormat for a numeric padding spin:
// Numbers don't lie, but they love to be zero-padded!DecimalFormat df = new DecimalFormat("0000000");
String paddedNumber = df.format(123); // "0000123"
StringUtils for Apache Fanboys
StringUtils takes care of all your padding blues:
// StringUtils shows, it ain't just about zeros. String padded = StringUtils.rightPad("text", 10);
String padded = StringUtils.leftPad("text", 10, 'z');
Formatter Class
Sometimes, String.format() just isn't enough. Say hello to Formatter class:
// For when String.format() starts feeling too "Main Stream."StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
fmt.format("%-10s", "text"); // "text "String padded = sb.toString();
fmt.close();