public class Divers {
public static void main(String args[]){
String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
System.out.format(format, \"FirstName\",
I was playing around with Mertuarez's elegant answer above and decided to post my version.
public class CenterString {
public static String center(String text, int len){
if (len <= text.length())
return text.substring(0, len);
int before = (len - text.length())/2;
if (before == 0)
return String.format("%-" + len + "s", text);
int rest = len - before;
return String.format("%" + before + "s%-" + rest + "s", "", text);
}
// Test
public static void main(String[] args) {
String s = "abcde";
for (int i = 1; i < 10; i++){
int max = Math.min(i, s.length());
for (int j = 1; j <= max; j++){
System.out.println(center(s.substring(0, j), i) + "|");
}
}
}
}
Output:
a|
a |
ab|
a |
ab |
abc|
a |
ab |
abc |
abcd|
a |
ab |
abc |
abcd |
abcde|
a |
ab |
abc |
abcd |
abcde |
a |
ab |
abc |
abcd |
abcde |
a |
ab |
abc |
abcd |
abcde |
a |
ab |
abc |
abcd |
abcde |
Practical differences from Mertuarez's code: