下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

我相信这就是他真正想要的:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

输出:

000Apple

其他回答

可以更快,然后克里斯勒彻回答时,大部分的字符串恰好有8个字符

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

在我的情况下,我的机器快了1/8。

我喜欢用零填充字符串的解决方案

String.format("%1$" + length + "s", inputString).replace(' ', '0');

with length = "8" and inputString = "Apple"

你可以用这个:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
String input = "Apple";
StringBuffer buf = new StringBuffer(input);

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

String output = buf.toString();
 StringUtils.leftPad(yourString, 8, '0');

这来自commons-lang。看到javadoc