-
繁华开满天机
阿帕奇StringUtils有几种方法:leftPad, rightPad, center和repeat.但请注意-正如其他人在这个答案 — String.format()而FormatterJDK中的类是更好的选择。在公用代码中使用它们。
-
素胚勾勒不出你
从Java 1.5开始,String.format()可用于左/右衬垫给定的字符串。public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}产出如下:Howto *
Howto*
-
www说
填充10个字符:String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');产出: *******foo
bar*******
longer*than*10*chars为密码字符显示“*”:String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');输出的长度与密码字符串相同: secret123
*********