下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
你可能得处理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 input = "Apple";
StringBuffer buf = new StringBuffer(input);
while (buf.length() < 8) {
buf.insert(0, '0');
}
String output = buf.toString();
我喜欢用零填充字符串的解决方案
String.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"
可以更快,然后克里斯勒彻回答时,大部分的字符串恰好有8个字符
int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);
在我的情况下,我的机器快了1/8。
在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做的方法)。它和其他的解决方案有点不同,我特别喜欢它。
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc