小编典典

如何在Java中填充字符串?

java

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

似乎应该在类似StringUtil的API中使用某些东西,但是我找不到能做到这一点的任何东西。


阅读 1505

收藏
2020-02-26

共2个答案

小编典典

有几种方法:leftPad,[rightPad](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#rightPad(java.lang.String,%20int)
centerrepeat

但请注意-如其他人所说的,并证明了这个答案 - String.format()FormatterJDK中的类是更好的选择。在公共代码上使用它们。

2020-02-26
小编典典

从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*
2020-02-26