Format a string with leading zeros in Java
This post will discuss how to format a string with leading zeros in Java.
1. Using String.format() method
The standard solution to format a string is to use the String.format() method, which takes printf-style format strings. To get a zero-padded string, you can use the '0' flag with width indicating the minimum number of characters to be written to the output.
|
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { String str = "1011101"; int width = 16; String formatted = String.format("%0" + width + "d", Integer.valueOf(str)); System.out.println(formatted); } } |
Output:
0000000001011101
2. Using Apache Commons Lang
Apache Commons Lang StringUtils utility class provides the leftPad() method that can left-pad a string with the specified character. You can use it as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String str = "1011101"; int size = 16; char padChar = '0'; String formatted = StringUtils.leftPad(str, size, padChar); System.out.println(formatted); } } |
Output:
0000000001011101
3. Using Guava Libaray
Guava’ Strings utility class provides the padStart() method that prepends a String with copies of the specified character to reach the specified length. You can use it as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import com.google.common.base.Strings; public class Main { public static void main(String[] args) { String str = "1011101"; int minLength = 16; char padChar = '0'; String formatted = Strings.padStart(str, minLength, '0'); System.out.println(formatted); } } |
Output:
0000000001011101
That’s all about formatting a string with leading zeros in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)