How to Pad a String in Java
Padding strings with spaces or a specific character is a common text output requirement. This is required when you want to generate a fixed format output even when the size of the data displayed are different. However there are no built-in Java functions for String padding. Using a third party library just for string padding is overkill!
The following Java program contains custom functions for right padding and left padding a string with a specific character. Run the program to see padding in action!
Code Example: How to Pad a String in Java
// Demo: How to right pad or left pad Strings in Java
public class PaddingDemo {
public static void main(String[] args) {
String input1 = "Hello World!";
String input2 = "Hi There!";
String output1 = padRight(input1,20,'*');
String output2 = padRight(input2,20,'*');
System.out.println(output1);
System.out.println(output2);
output1 = padLeft(input1,20,'*');
output2 = padLeft(input2,20,'*');
System.out.println(output1);
System.out.println(output2);
}
// Right pad a string with the specified character
public static String padRight(String s, int size,char pad) {
StringBuilder builder = new StringBuilder(s);
while(builder.length()<size) {
builder.append(pad);
}
return builder.toString();
}
// Left pad a string with the specified character
public static String padLeft(String s, int size,char pad) {
StringBuilder builder = new StringBuilder(s);
builder = builder.reverse(); // reverse initial string
while(builder.length()<size) {
builder.append(pad); // append at end
}
return builder.reverse().toString(); // reverse again!
}
}
The output generated is,
Hello World!******** Hi There!*********** ********Hello World! ***********Hi There!