Percy

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

java

例如,这是字符串:

"Apple"

并且我想添加零以填写8个字符:

"000Apple"

我该怎么办?


阅读 356

收藏
2020-12-01

共2个答案

小编典典

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

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

(有效,只要您的字符串不超过8个字符。)

2020-12-01
小编典典

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);
    }
}
2020-12-01