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

前端 未结 5 1381
梦谈多话
梦谈多话 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 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
    

提交回复
热议问题