public class Divers {
public static void main(String args[]){
String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
System.out.format(format, \"FirstName\",
Converted the code found at https://www.leveluplunch.com/java/examples/center-justify-string/ into a handy, small one-line function:
public static String centerString (int width, String s) {
return String.format("%-" + width + "s", String.format("%" + (s.length() + (width - s.length()) / 2) + "s", s));
}
Usage:
public static void main(String[] args){
String out = centerString(10, "afgb");
System.out.println(out); //Prints " afgb "
}
I think it's a very neat solution that's worth mentioning.