下面是字符串,例如:

"Apple"

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

"000Apple"

我该怎么做呢?


当前回答

在Java中:

String zeroes="00000000";
String apple="apple";

String result=zeroes.substring(apple.length(),zeroes.length())+apple;

在Scala中:

"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}

你也可以在Java 8中探索一种使用流和简化的方法(类似于我用Scala做的方法)。它和其他的解决方案有点不同,我特别喜欢它。

其他回答

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

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

我相信这就是他真正想要的:

String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple"); 

输出:

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