假设我有几个变量,我想格式化它们,使它们都是对齐的,但变量的长度不同。例如:
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我该怎么做呢?提前谢谢。
发布于 2017-03-27 04:22:30
使用固定大小格式:
使用固定大小的格式化字符串的
允许以具有固定大小的列的表格外观打印字符串:
String rowsStrings[] =新String[] {"1","1234","1234567","123456789"};String column1Format = "%-3.3s";//固定大小3个字符,左对齐字符串column2Format = "%-8.8s";//固定大小8个字符,左对齐字符串column3Format = "%6.6s";//固定大小6个字符,右对齐字符串formatInfo = column1Format +“”+ column2Format +“”+ column3Format;for(int i= 0;i< rowsStrings.length;i++) { System.out.format(formatInfo,rowsStringsi,rowsStringsi,rowsStringsi);System.out.println();}
输出:
111231234123123 1234567 123456 123123 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);发布于 2017-03-27 05:28:09
将负号放在格式说明符的前面,这样它就不会在浮点值的左侧打印5个空格,而是会调整右侧的空格,直到您找到理想的位置。应该没问题的
发布于 2017-03-27 04:22:07
您可以找到最长的String,然后使用Apache commons-lang StringUtils来leftPad您的两个String。像这样,
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.56https://stackoverflow.com/questions/43034015
复制相似问题