下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

使用方法String::repeat的解决方案(Java 11)

String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;

如果需要,将8更改为其他数字或将其参数化

其他回答

你可以用这个:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
String input = "Apple";
StringBuffer buf = new StringBuffer(input);

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

String output = buf.toString();

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

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

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

你可能得处理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;
    }
}

如果你想用纯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