下面是字符串,例如:

"Apple"

我想加零来填充8个字符:

"000Apple"

我该怎么做呢?


当前回答

String input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();

其他回答

使用方法String::repeat的解决方案(Java 11)

String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;

如果需要,将8更改为其他数字或将其参数化

这并不漂亮,但很有效。如果你有apache commons,我建议你使用它

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}

你可以用这个:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")

使用Apache Commons StringUtils。leftPad(或者查看代码来创建自己的函数)。

这是快速的,适用于任何长度。

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}