下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

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

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

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

其他回答

我也遇到过类似的情况,我用了这个;它是非常简洁的,你不需要处理长度或其他库。

String str = String.format("%8s","Apple");
str = str.replace(' ','0');

简单而利落。字符串格式返回“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;
    }
}
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;
    }
}
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 input = "Apple";
StringBuffer buf = new StringBuffer(input);

while (buf.length() < 8) {
  buf.insert(0, '0');
}

String output = buf.toString();