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

前端 未结 3 1697
名媛妹妹
名媛妹妹 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:29

    consider using a negative number for your length specifier: %-20s. For example:

       public static void main(String[] args) {
         String[] firstNames = {"Pete", "Jon", "Fred"};
         String[] lastNames = {"Klein", "Jones", "Flinstone"};
         String phoneNumber = "555-123-4567";
    
          for (int i = 0; i < firstNames.length; i++) {
            String foo = String.format("%-20s %s", lastNames[i] + ", " + 
                 firstNames[i], phoneNumber);
            System.out.println(foo);
          }   
       }
    

    returns

    Klein, Pete          555-123-4567
    Jones, Jon           555-123-4567
    Flinstone, Fred      555-123-4567
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-15 07:50

    The only alternative is loop the names list, calculate the maximum length of the String, and add whitespaces as needed after every name to ensure that all the numbers begin at the same column.

    Using tabs has the disavantage that you cannot know a priori how many whitespace are equivalent to a tab, since it is dependent of the editor.

    0 讨论(0)
提交回复
热议问题