有没有一些简单的方法来填充Java中的字符串?
Java中,如何在Java中填充字符串?
自Java 1.5以来,String.format()可用于左/右填充给定的字符串。
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}
/*
output :
Howto *
Howto*
*/
如果你需要与其他字符(不是空格)怎么办?可以使用以下代码:
填充至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
*********