下面是字符串,例如:

"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;
    }
}

其他回答

 StringUtils.leftPad(yourString, 8, '0');

这来自commons-lang。看到javadoc

使用Guava的Strings实用程序类:

Strings.padStart("Apple", 8, '0');
public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}

我喜欢用零填充字符串的解决方案

String.format("%1$" + length + "s", inputString).replace(' ', '0');

with length = "8" and inputString = "Apple"

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