下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"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做的方法)。它和其他的解决方案有点不同,我特别喜欢它。
其他回答
使用Apache Commons StringUtils。leftPad(或者查看代码来创建自己的函数)。
使用Guava的Strings实用程序类:
Strings.padStart("Apple", 8, '0');
你可以用这个:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。
while(str.length() < desired_length)
str = '0'+str;