How do I properly align using String.format in Java?

前端 未结 5 1555
梦谈多话
梦谈多话 2021-01-16 09:22

Let\'s say I have a couple variable and I want to format them so they\'re all aligned, but the variables are different lengths. For example:

String a = \"abc         


        
5条回答
  •  一个人的身影
    2021-01-16 09:59

    Use fixed size format:

    Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

    String rowsStrings[] = new String[] {"1", 
                                         "1234", 
                                         "1234567", 
                                         "123456789"};
    
    String column1Format = "%-3.3s";  // fixed size 3 characters, left aligned
    String column2Format = "%-8.8s";  // fixed size 8 characters, left aligned
    String column3Format = "%6.6s";   // fixed size 6 characters, right aligned
    String formatInfo = column1Format + " " + column2Format + " " + column3Format;
    
    for(int i = 0; i < rowsStrings.length; i++) {
        System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
        System.out.println();
    } 
    

    Output:

    1   1             1
    123 1234       1234
    123 1234567  123456
    123 12345678 123456
    

    In your case you could find the maximum length of the strings you want to display and use that to create the appropriate format information, for example:

    // find the max length
    int maxLength = Math.max(a.length(), b.length());
    
    // add some space to separate the columns
    int column1Length = maxLength + 2;
    
    // compose the fixed size format for the first column
    String column1Format = "%-" + column1Length + "." + column1Length + "s";
    
    // second column format
    String column2Format = "%10.2f";
    
    // compose the complete format information
    String formatInfo = column1Format + " " + column2Format;
    
    System.out.format(formatInfo, a, price);
    System.out.println();
    System.out.format(formatInfo, b, price);
    

提交回复
热议问题