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

前端 未结 5 1371
梦谈多话
梦谈多话 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);
    
    0 讨论(0)
  • 2021-01-16 10:06

    You can achieve it as below-

        String a = "abcdef";
        String b = "abcdefhijk";
        double price = 4.56;
    
        System.out.println(String.format("%-10s %-10.2f", a, price));
        System.out.println(String.format("%-10s %-10.2f", b, price));
    

    output:

       abcdef     4.56      
       abcdefhijk 4.56
    
    0 讨论(0)
  • 2021-01-16 10:18

    You can find the longest String, and then use Apache commons-lang StringUtils to leftPad both of your String(s). Something like,

    int len = Math.max(a.length(), b.length()) + 2;
    a = StringUtils.leftPad(a, len);
    b = StringUtils.leftPad(b, len);
    

    Or, if you can't use StringUtils - you could implement leftPad. First a method to generate String of whitespace. Something like,

    private static String genString(int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(' ');
        }
        return sb.toString();
    }
    

    Then use it to implement leftPad - like,

    private static String leftPad(String in, int len) {
        return new StringBuilder(in) //
                .append(genString(len - in.length() - 1)).toString();
    }
    

    And, I tested it like,

    int len = Math.max(a.length(), b.length()) + 2;
    System.out.format("%s %.2f%n", leftPad(a, len), price);
    System.out.format("%s %.2f%n", leftPad(b, len), price);
    

    Which outputs (as I think you wanted)

    abcdef      4.56
    abcdefhijk  4.56
    
    0 讨论(0)
  • 2021-01-16 10:20
    private String addEnoughSpacesInBetween(String firstStr, String secondStr){
    
        if (!firstStr.isEmpty() && !secondStr.isEmpty()){
    
            String space = " ";
    
            int totalAllowed = 55;
    
            int multiplyFor = totalAllowed - (firstStr.length() + secondStr.length());
    
            return StringUtils.repeat(space,multiplyFor);
        }
        return null;
    }
    
    0 讨论(0)
  • 2021-01-16 10:26

    Put negative sign in front of your format specifier so instead of printing 5 spaces to the left of your float value, it adjusts the space on the right until you find the ideal position. It should be fine

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