java如何使用字符串将字符串居中。总体安排
public class Divers {
public static void main(String args[]){
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "FirstName", "Init.", "LastName");
System.out.format(format, "Real", "", "Gagnon");
System.out.format(format, "John", "D", "Doe");
String ex[] = { "John", "F.", "Kennedy" };
System.out.format(String.format(format, (Object[])ex));
}
}
输出:
|FirstName |Init. |LastName |
|Real | |Gagnon |
|John |D |Doe |
|John |F. |Kennedy |
我希望输出居中。如果不使用“-”标记,则输出将向右对齐
我在API中找不到居中文本的标志
This这篇文章有一些关于格式的信息,但没有任何关于格式的信息
# 1 楼答案
下面是使用apache commons lang StringUtils的答案
请注意,您必须将jar文件添加到构建路径中。如果您使用的是maven,请确保在依赖项中添加commons lang
# 2 楼答案
自Java 11以来的“一行程序”
其中:
" ".repeat(m)
-填充空间李>n - s.length()
-要填充的差异大小李>diff / 2
-产生前缀大小(例如5/2=2)(diff + 1) / 2
-产生后缀大小(例如(5+1)/2=3)自Java 8以来
Java8没有
" ".repeat(10)
方法。所以只需将
" ".repeat(10)
替换为Java8模拟。见https://stackoverflow.com/a/57514604/601844,以及使用与Java 11相同的☝️) alg:
# 3 楼答案
我很快就搞定了。现在可以在
String.format
中使用StringUtils.center(String s, int size)
# 4 楼答案
# 5 楼答案
将https://www.leveluplunch.com/java/examples/center-justify-string/处的代码转换为一个方便的小单行函数:
用法:
我认为这是一个非常简洁的解决方案,值得一提
# 6 楼答案
我在玩弄上面Mertuarez优雅的回答,决定发布我的版本
输出:
与Mertuarez代码的实际差异: