Left padding a String with Zeros [duplicate]

2018-12-31 18:43发布

This question already has an answer here:

I've seen similar questions here and here.

But am not getting how to left pad a String with Zero.

input: "129018" output: "0000129018"

The total output length should be TEN.

20条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 19:40
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 19:41

The solution by Satish is very good among the expected answers. I wanted to make it more general by adding variable n to format string instead of 10 chars.

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

This will work in most situations

查看更多
登录 后发表回答