下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

 StringUtils.leftPad(yourString, 8, '0');

这来自commons-lang。看到javadoc

其他回答

在Java中:

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

在Scala中:

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

你也可以在Java 8中探索一种使用流和简化的方法(类似于我用Scala做的方法)。它和其他的解决方案有点不同,我特别喜欢它。

 StringUtils.leftPad(yourString, 8, '0');

这来自commons-lang。看到javadoc

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

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

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

下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。

while(str.length() < desired_length)
  str = '0'+str;

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

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