有一些简单的方法来填充字符串在Java?

似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。


当前回答

s =字符串填充 n =期望长度 c = Char到pad

private String padStart( String s, int n, char c ){
    if( n <= 0 ) return s;
    else return String.format("%" + n + "s", s).replace(' ', c);
}

其他回答

在Dzone上找到的

用零填充:

String.format("|%020d|", 93); // prints: |00000000000000000093|

Apache StringUtils有几个方法:leftPad, rightPad, center和repeat。

但是请注意,正如其他人在这个回答中提到和演示的那样,JDK中的String.format()和Formatter类是更好的选择。使用它们而不是公共代码。

另一种利用递归的解决方案。

这与所有JDK版本兼容,不需要外部库:

private static String addPadding(final String str, final int desiredLength, final String padBy) {
    String result = str;
    if (str.length() >= desiredLength) {
        return result;
    } else {
        result += padBy;
        return addPadding(result, desiredLength, padBy);
    }
}

注意:这个解决方案将附加填充,与一个小调整,你可以前缀填充值。

填充到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
  *********

这里有一个并行版本的你有很长的字符串:-)

int width = 100;
String s = "129018";

CharSequence padded = IntStream.range(0,width)
            .parallel()
            .map(i->i-(width-s.length()))
            .map(i->i<0 ? '0' :s.charAt(i))
            .collect(StringBuilder::new, (sb,c)-> sb.append((char)c), (sb1,sb2)->sb1.append(sb2));