猿问

如何用Java填充字符串?

如何用Java填充字符串?

有什么简单的方法可以在Java中填充字符串吗?

似乎应该出现在一些类似StringUtil的API中,但是我找不到任何这样的东西。


至尊宝的传说
浏览 1698回答 3
3回答

繁华开满天机

阿帕奇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   *********
随时随地看视频慕课网APP

相关分类

Java
我要回答