下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
public static String lpad(String str, int requiredLength, char padChar) {
if (str.length() > requiredLength) {
return str;
} else {
return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
}
}
其他回答
你可以使用:
String.format("%08d", "Apple");
这似乎是最简单的方法,不需要任何外部库。
你可能得处理edgecase。这是一个泛型方法。
public class Test {
public static void main(String[] args){
System.out.println(padCharacter("0",8,"hello"));
}
public static String padCharacter(String c, int num, String str){
for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
return str;
}
}
我相信这就是他真正想要的:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
输出:
000Apple
你可以用这个:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
在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做的方法)。它和其他的解决方案有点不同,我特别喜欢它。