Left padding a String with Zeros
Want to pad your string with zeros in no time? Use String.format()
:
In this code, n
is your total desired width and str
is your numeric string. Please ensure str
is positive. Negativity is frowned upon in this community.
What about the non-numeric kids in town? Fret not! Mix up String.format()
and .replace()
to serve your needs:
Sometimes, life demands more control, especially when your string is playing hard to get with special characters. In such cases, call up your trusty StringBuilder
friend:
Advanced techniques for the ninja coder
How to pick your path
Before you dive in, take a moment to know your input:
Want to dress up numeric strings? Gracefully use the String.format()
with "%0Nd"
. Excels in simplicity, efficiency, and gets the job done.
Working with alphanumeric or non-numeric strings? Try the charming StringUtils.leftPad(input, length, '0')
or handle things manually with StringBuilder
. Proves handy when dealing with multilingual text or if you are okay to make use of external libraries.
For the unexpected guest
Not sure if your guest will be numeric? Avoid the Integer.parseInt()
paranoia:
Starting from Java 11, meet your new efficient friend: the String.repeat()
method.
Binary made easy
Got an integer’s binary representation that needs a makeover? Try this:
Was this article helpful?