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

新手上路,请多包涵

这是字符串,例如:

 "Apple"

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

 "000Apple"

我该怎么做?

原文由 Roy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 447
2 个回答

如果您必须在没有图书馆帮助的情况下这样做:

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

(只要您的字符串不超过 8 个字符,就可以工作。)

原文由 Chris Lercher 发布,翻译遵循 CC BY-SA 2.5 许可协议

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

原文由 Alex Rashkov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题