下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

在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做的方法)。它和其他的解决方案有点不同,我特别喜欢它。

其他回答

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

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

你可以用这个:

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

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

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

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

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

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}
public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}