C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pad, right: The code -10s adds right-padding to a string. We must specify the minus sign here.
Pad, left: The code 10d adds left padding to an integer ("s" would handle a string).
Result: The format string applies padding to two values at once. This is efficient and correct.
Java program that uses padding, String.format
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);
}
}
}
Output
red 42
orange 100
blue 200
green 90
Result: The string "Ulysses" is 7 chars, so 3 space chars are added to the start to get to 10 chars.
Java program that uses padding, right-justification
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("]");
}
}
Output
[ Ulysses]
Java program that uses padding, left-justification
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("|");
}
}
Output
|Finnegans Wake |
And: Custom methods (like padLeft and padRight) would be easier to call in a program.
However: With methods that only pad one value, an entire line cannot be composed in one statement. This would likely be less efficient.