A padded string
has leading or trailing spaces up to a certain number of characters. But no built-in "padding" method is available on the String
class
.
Instead, we implement padding with format strings and the String.format
method. We can specify left and right padding. We can pad strings and numbers.
This program left-justifies color names and right-justifies a parallel array of ints. We do this with just one format string
.
string
. We must specify the minus sign here.string
).string
applies padding to two values at once. This is efficient and correct.public class Program { public static void main(String[] args) { String[] colors = { "red", "orange", "blue", "green" }; int[] numbers = { 42, 100, 200, 90 }; // Loop over both arrays. for (int i = 0; i < colors.length; i++) { // Left-justify the color string. // ... Right-justify the number. String line = String .format("%1$-10s %2$10d", colors[i], numbers[i]); System.out.println(line); } } }red 42 orange 100 blue 200 green 90
This program shows how the String.format
method can be used to right-justify a string
. It uses a total width of 10 chars.
string
"Ulysses" is 7 chars, so 3 space chars are added to the start to get to 10 chars.public class Program { public static void main(String[] args) { String title = "Ulysses"; // Pad this string with spaces on the left to 10 characters. String padded = String.format("%1$10s", title); // Display result. System.out.print("["); System.out.print(padded); System.out.println("]"); } }[ Ulysses]
Here we left-justify a string
. We expand the string
to 20 chars, adding spaces on the right as needed. We must specify the minus sign.
public class Program { public static void main(String[] args) { String title = "Finnegans Wake"; // Left-justify this title to 20 characters. String padded = String.format("%1$-20s", title); // Our result. System.out.print("|"); System.out.print(padded); System.out.println("|"); } }|Finnegans Wake |
The String.format
method is an effective way of aligning text with padding. But we could wrap these String.format
calls in methods.
padLeft
and padRight
) would be easier to call in a program.With String.format
we apply padding to strings and numbers. We can pad many values at once with the format string
syntax. This is powerful but can be complex.