下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

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

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

其他回答

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

public class PaddingLeft {
    public static void main(String[] args) {
        String input = "Apple";
        String result = "00000000" + input;
        int length = result.length();
        result = result.substring(length - 8, length);
        System.out.println(result);
    }
}
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;
    }
}

你可以用这个:

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

如果你想用纯Java编写程序,你可以遵循下面的方法,或者有很多String Utils可以帮助你更好地使用更高级的功能。

使用一个简单的静态方法可以实现如下所示。

public static String addLeadingText(int length, String pad, String value) {
    String text = value;
    for (int x = 0; x < length - value.length(); x++) text = pad + text;
    return text;
}

你可以使用上面的方法addLeadingText(长度,填充文本,你的文本)

addLeadingText(8, "0", "Apple");

输出是000Apple