How do I pad a String with spaces or other characters?
Author: Deron Eriksson
Description: This Java example shows how to pad a String with spaces or other characters.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The leftPad(), rightPad(), and center() methods of the StringUtils class in Commons LangS make it easy to pad a String with spaces or other characters to the left, right, or both sides of the String. Typically, to use these methods, you specify the String that you'd like to pad and the total size of the finished String. This total size includes the starting length of the String. You can specify an alternative padding character or characters via a third argument to these methods. The PadTest class demonstrates this.

PadTest.java

package test;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

public class PadTest {

	public static void main(String[] args) throws IOException {

		String str = "Pad Me";
		System.out.printf("%-15s[%s]\n", "Original:", str);

		System.out.println();

		System.out.printf("%-15s[%s]\n", "Left Padded:", StringUtils.leftPad(str, 10));
		System.out.printf("%-15s[%s]\n", "Right Padded:", StringUtils.rightPad(str, 10));
		System.out.printf("%-15s[%s]\n", "Centered:", StringUtils.center(str, 10));

		System.out.println();

		System.out.printf("%-15s[%s]\n", "Left Padded:", StringUtils.leftPad(str, 10, "*"));
		System.out.printf("%-15s[%s]\n", "Right Padded:", StringUtils.rightPad(str, 10, "*"));
		System.out.printf("%-15s[%s]\n", "Centered:", StringUtils.center(str, 10, "*"));

	}

}

The output from executing PadTest is shown below.

Results

Original:      [Pad Me]

Left Padded:   [    Pad Me]
Right Padded:  [Pad Me    ]
Centered:      [  Pad Me  ]

Left Padded:   [****Pad Me]
Right Padded:  [Pad Me****]
Centered:      [**Pad Me**]