下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

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

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

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

其他回答

这是快速的,适用于任何长度。

public static String prefixZeros(String value, int len) {
    char[] t = new char[len];
    int l = value.length();
    int k = len-l;
    for(int i=0;i<k;i++) { t[i]='0'; }
    value.getChars(0, l, t, k);
    return new String(t);
}

你可以用这个:

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

你可能得处理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;
    }
}
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 str = String.format("%8s","Apple");
str = str.replace(' ','0');

简单而利落。字符串格式返回“Apple”,因此在用零替换空格后,它会给出所需的结果。