How to center a string using String.format?

后端 未结 9 1599
陌清茗
陌清茗 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 13:07

    Here's the answer using apache commons lang StringUtils.

    Please note that you have to add the jar file to the build path. If you are using maven make sure to add commons lang in the dependencies.

    import org.apache.commons.lang.StringUtils;
    public class Divers {
      public static void main(String args[]){
    
        String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
        System.out.format(format, "FirstName", "Init.", "LastName");
        System.out.format(format,StringUtils.center("Real",10),StringUtils.center("",10),StringUtils.center("Gagnon",20);
    
        System.out.format(String.format(format, (Object[])ex));
      }
    }
    

提交回复
热议问题