如何格式化带有前导零的Java字符串?

2022-08-31 05:40:16

下面是字符串,例如:

"Apple"

我想添加零来填写8个字符:

"000Apple"

我该怎么做?


答案 1
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);
    }
}

答案 2

如果您必须在没有库帮助的情况下执行此操作:

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

(有效,只要你的字符串长度不超过 8 个字符。