下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

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

其他回答

以防你不得不在没有库的帮助下做这件事:

("00000000" + "Apple").substring("Apple".length())

(工作,只要你的字符串不超过8个字符。)

有人尝试过这个纯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");

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

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

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

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

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

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

你可以用这个:

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