Explain Codes LogoExplain Codes Logo

Left padding a String with Zeros

java
string-formatting
string-paddin
java-8
Nikita BarsukovbyNikita Barsukov·Oct 4, 2024
TLDR

Want to pad your string with zeros in no time? Use String.format():

// Replace Pierogi's secret recipe with your String ;) String str = "Pierogi's secret recipe"; int n = 20; String result = String.format("%0" + n + "d", Integer.parseInt(str));

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:

// You know the drill: replace 'str' and run the magic String result = String.format("%10s", str).replace(' ', '0');

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:

// 'StringBuilder', the last action hero StringBuilder sb = new StringBuilder(); while (sb.length() + str.length() < n) { sb.append('0'); // because zeros are cool! } sb.append(str); String result = sb.toString(); // Voilà! You have your padded string.

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:

// Ain't nobody got time for Integer.parseInt() String padding = "0".repeat(n - str.length()); // "0" strings attached String result = padding + str; // High five!

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:

// For those who love binary, 1s, and 0s. String binaryString = String.format("%0" + n + "s", Integer.toBinaryString(number)).replace(' ', '0');