下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

我也遇到过类似的情况,我用了这个;它是非常简洁的,你不需要处理长度或其他库。

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

简单而利落。字符串格式返回“Apple”,因此在用零替换空格后,它会给出所需的结果。

其他回答

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

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

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

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

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

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

String output = buf.toString();

你可以使用字符串。格式化方法,用于另一个答案生成一个0的字符串,

String.format("%0"+length+"d",0)

这可以通过动态调整格式字符串中前导0的数量来应用于您的问题:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

这仍然是一个混乱的解决方案,但优点是可以使用整数参数指定结果字符串的总长度。

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

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

输出:

000Apple