如何用Java填充字符串?有什么简单的方法可以在Java中填充字符串吗?似乎应该出现在一些类似StringUtil的API中,但是我找不到任何这样的东西。
3 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
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说
TA贡献1775条经验 获得超8个赞
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 *********
添加回答
举报
0/150
提交
取消
