Explain Codes LogoExplain Codes Logo

How can I pad a String in Java?

java
padding
string-formatting
guava
Nikita BarsukovbyNikita Barsukov·Aug 14, 2024
TLDR

Right-pad a string to a specific width with spaces using String.format():

// Her eyes were wide open... as wide as the padding of this string. String padded = String.format("%-10s", "text"); // "text "

For left-pad with zeros:

// 123 steps to go... wait! Let's zero-pad our journey. String paddedZero = String.format("%010d", 123); // "0000000123"

Padding Techniques

String.format() for dynamic padding

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();