Left padding a String with Zeros
To left pad a String
with zeros in Java, you can use the String.format()
method and the %0Nd
format specifier, where N
is the total length of the padded string.
For example, to left pad a string with 5 zeros, you can use the following code:
String s = "123";
String padded = String.format("%05d", Integer.parseInt(s)); // padded is "00123"
The %05d
format specifier tells the String.format()
method to format the integer value as a decimal number with a total length of 5, and to pad the number with zeros on the left if necessary.
You can also use the DecimalFormat
class to left pad a string with zeros. For example:
String s = "123";
DecimalFormat df = new DecimalFormat("00000");
String padded = df.format(Integer.parseInt(s)); // padded is "00123"
Note that in both examples, the input string s
is first converted to an integer using the Integer.parseInt()
method. If the input string is not a valid integer, the parseInt()
method will throw a NumberFormatException
.
I hope this helps! Let me know if you have any questions.