我在这里和这里都见过类似的问题。

但我不知道如何左垫字符串与零。

输入:“129018” 输出:“0000129018”

总输出长度应为10。


当前回答

你可以使用apache commons StringUtils

StringUtils.leftPad("129018", 10, "0");

https://commons.apache.org/proper/commons lang/javadocs/api - 2.6 - / - org/apache/commons/lang/stringutils.html # leftPad (% 20 int,以% 20字符)

其他回答

String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")

第二个参数是期望的输出长度

"0"是填充字符

String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);

我用过这个:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

结果:00123

我希望它对你有用!

右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)

这是另一种方法:

int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)