How to center a string using String.format?

后端 未结 9 1602
陌清茗
陌清茗 2020-11-30 12:28
public class Divers {
  public static void main(String args[]){

     String format = \"|%1$-10s|%2$-10s|%3$-20s|\\n\";
     System.out.format(format, \"FirstName\",         


        
9条回答
  •  青春惊慌失措
    2020-11-30 12:54

    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.

提交回复
热议问题