在 Java 中,可以使用 String.format() 方法和 String.format('%0nd', num) 格式化字符串实现左补零。

例如,如果要将一个整数 num 格式化为长度为 5 的字符串,并在左侧补零,可以使用以下代码:

int num = 123;
String str = String.format('%05d', num);
System.out.println(str); // 输出 00123

其中,'%05d' 表示格式化为 5 位长度的字符串,并在左侧补零。如果要将 num 格式化为其他长度的字符串,只需要将数字 5 替换为所需的长度即可。

Java 左补零:使用 String.format() 实现字符串填充

原文地址: https://www.cveoy.top/t/topic/nHMW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录