在Java中如何使用String.format正确对齐?

3

假设我有几个变量,我想对它们进行格式化,使它们对齐,但这些变量的长度不同。例如:

String a = "abcdef";
String b = "abcdefhijk";

我也有一个价格。
double price = 4.56;

我应该如何格式化字符串,使得无论其长度如何,它们都可以左右对齐?
System.out.format("%5s %10.2f", a, price);
System.out.format("%5s %10.2f", b, price);

例如,上述代码将输出类似于以下内容:
abcdef       4.56
abcdefhijk       4.56

但我想要它输出类似于这样的内容:
abcdef      4.56
abcdefhijk  4.56

我该如何做呢?提前感谢。
5个回答

7

使用固定大小格式:

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

在您的情况下,您可以找到要显示的字符串的最大长度,并使用它来创建适当的格式信息,例如:

// 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);

我认为OP的问题是在ab的最大长度未知的情况下。 - Elliott Frisch
@LorisSecuro 嗯,有趣。我想我可以这样做,唯一的问题是我们在课堂上根本没有学过这个,所以我不确定是否允许使用它。一直在寻找一种仅使用String.format()来完成它的方法,但我猜可能没有办法了?谢谢。 - blyter
@blyter 我的回答使用了你在问题中使用的相同方法,没有添加新的概念。 - Loris Securo
@ElliottFrisch 添加了一个示例来查找和使用最大长度。 - Loris Securo

1
在格式说明符前加上负号,这样就不会在浮点值左侧打印5个空格,而是将空格调整到右侧,直到找到理想位置。这应该没问题。

1
您可以按以下方式实现-
    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));

输出:

   abcdef     4.56      
   abcdefhijk 4.56

0
你可以找到最长的字符串,然后使用Apache commons-lang StringUtilsleftPad你的两个字符串。就像这样,
int len = Math.max(a.length(), b.length()) + 2;
a = StringUtils.leftPad(a, len);
b = StringUtils.leftPad(b, len);

或者,如果您无法使用StringUtils - 您可以实现leftPad。首先是生成空格String的方法。类似于以下内容:

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

然后使用它来实现leftPad - 类似于,
private static String leftPad(String in, int len) {
    return new StringBuilder(in) //
            .append(genString(len - in.length() - 1)).toString();
}

而且,我像这样进行了测试:

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);

输出结果(我想这就是你想要的)

abcdef      4.56
abcdefhijk  4.56

0
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;
}

1
你应该添加一些解释。 - m02ph3u5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接