以下代码段将教您在要将字符串打印到控制台时如何以左,右或中心对齐方式对齐字符串。我们将使用printf(String format, Object... args)方法打印字符串。的format说明符/参数定义串将如何被格式化为输出和args是将要格式化的值。
该format参数/符包括标记,宽度,精度和转换字符在下面示出的顺序。符号中的方括号表示该零件是可选参数。% [flags] [width] [.precision] conversion-character标志描述-左对齐输出,未指定时默认为右对齐
+在数字上打印(+)或(-)符号
0零填充数值
,大于1000的逗号分组分隔符
空格将为-负值输出()符号,如果为正则输出空格转换次数描述s字符串,使用S大写字母将字符串大写
c字符,使用C大写字母大写
d整数byte,short,integer,long
f浮点数:float,double
n新队
宽度:定义用于打印参数值的字段宽度。它还表示
要输出到输出的最小字符数。
精度:对于浮点转换,精度定义浮点值中精度的位数。对于字符串值,这将提取子字符串。
为了使输出的字符串居中,我们使用StringUtils.center()Apache Commons Lang库中的方法。此方法将中心对准串str中的一个较大的字符串size使用默认空格字符(”“)。您可以提供第三个参数来定义自己的空格字符/字符串。package org.nhooo.example.lang;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
public class StringAlignment {
private static Object[][] people = {
{"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
{"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
{"Carol", LocalDate.of(1992, Month.JULY, 24)},
{"Ted", LocalDate.of(2006, Month.MARCH, 13)},
};
public static void main(String[] args) {
String nameFormat = "| %1$-20s | ";
String dateFormat = " %2$tb %2$td, %2$tY | ";
String ageFormat = " %3$3s |%n";
String format = nameFormat.concat(dateFormat).concat(ageFormat);
String line = new String(new char[48]).replace('\0', '-');
System.out.println(line);
System.out.printf("|%s|%s|%s|%n",
StringUtils.center("Name", 22),
StringUtils.center("Birth Date", 16),
StringUtils.center("Age", 6));
System.out.println(line);
for (Object[] data : people) {
System.out.printf(format,
data[0], data[1],
ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
}
System.out.println(line);
}
}
这是上面的代码片段的输出:------------------------------------------------
| Name | Birth Date | Age |
------------------------------------------------
| Alice | Jan 01, 2000 | 17 |
| Bob | Dec 15, 1989 | 27 |
| Carol | Jul 24, 1992 | 24 |
| Ted | Mar 13, 2006 | 10 |
------------------------------------------------
Maven依赖
org.apache.commons
commons-lang3
3.6