How to use String.format() in Java to replicate tab “\t”?

前端 未结 3 1867
名媛妹妹
名媛妹妹 2020-12-15 07:19

I\'m printing data line by line and want it to be organized like a table.

I initially used firstName + \", \" + lastName + \"\\t\" + phoneNumber.

<
3条回答
  •  太阳男子
    2020-12-15 07:39

    Try putting the width into second placeholder with - sign for right padding as:

      String.format("%s, %-20s %s", firstName, lastName, phoneNumber)
    

    This will give the specified width to the second argument(last name) with right padding and phone number will start after the specified width string only.

    EDIT: Demo:

    String firstName = "John";
    String lastName = "Smith";
    String phoneNumber = "1234456677";
    System.out.println(String.format("%s, %-20s %s",firstName, lastName, phoneNumber));
    

    prints:

    John, Smith               1234456677

提交回复
热议问题