下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

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

其他回答

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

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

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

你可以使用:

String.format("%08d", "Apple");

这似乎是最简单的方法,不需要任何外部库。

使用Guava的Strings实用程序类:

Strings.padStart("Apple", 8, '0');

你可以使用字符串。格式化方法,用于另一个答案生成一个0的字符串,

String.format("%0"+length+"d",0)

这可以通过动态调整格式字符串中前导0的数量来应用于您的问题:

public String leadingZeros(String s, int length) {
     if (s.length() >= length) return s;
     else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}

这仍然是一个混乱的解决方案,但优点是可以使用整数参数指定结果字符串的总长度。

可以更快,然后克里斯勒彻回答时,大部分的字符串恰好有8个字符

int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);

在我的情况下,我的机器快了1/8。