下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

使用Guava的Strings实用程序类:

Strings.padStart("Apple", 8, '0');

其他回答

你可以使用:

String.format("%08d", "Apple");

这似乎是最简单的方法,不需要任何外部库。

你可以用这个:

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

有人尝试过这个纯Java解决方案吗(没有SpringUtils):

//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros. 
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string. 
String.format("%1$10s", "mystring" ).replace(" ","0");

不幸的是,这个解决方案只有在字符串中没有空格时才有效。

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

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

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

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

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