如何在Java中使用String.format正确对齐? [英] How do I properly align using String.format in Java?
问题描述
比方说,我有几个变量,我想格式化它们,以便它们全部对齐,但是变量的长度不同.例如:
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 = "abcdef";
String b = "abcdefhijk";
我也有价格.
double price = 4.56;
我怎么能格式化它,所以不管String多久,它们都以两种方式对齐?
How would I be able to format it so no matter how long the String is, they are aligned either way?
System.out.format("%5s %10.2f", a, price);
System.out.format("%5s %10.2f", b, price);
例如,上面的代码将输出如下内容:
For example, the code above would output something like this:
abcdef 4.56
abcdefhijk 4.56
但是我希望它输出如下内容:
But I want it to output something like this:
abcdef 4.56
abcdefhijk 4.56
我将如何去做?预先感谢.
How would I go about doing so? Thanks in advance.
推荐答案
使用固定大小格式:
使用固定大小的格式字符串可以将字符串打印在 具有固定大小的列的表格外观:
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();
}
输出:
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);
这篇关于如何在Java中使用String.format正确对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!