How to add padding to a String in Java
This post will discuss how to add padding to a String in Java.
1. Using String.format() method
A common solution to left/right pad a string with spaces is using the String.format() method. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class Main { public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); } public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } public static void main(String[] args) { String s = "ABC"; int n = 5; System.out.println(padLeft(s, n)); // " ABC" System.out.println(padRight(s, n)); // "ABC " } } |
If your string is numeric, you can pad it with zeros by converting it to an integer:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static String padLeft(String s, int n) { return String.format("%0" + n + "d", Integer.parseInt(s)); } public static void main(String[] args) { String s = "123"; int n = 5; System.out.println(padLeft(s, n)); // 00123 } } |
2. Using Apache Commons StringUtils class
Alternatively, you can leverage Apache Commons Lang’s StringUtils class leftPad() and rightPad() utility methods, which can add specified padding to the start and end of a string, respectively.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String str = "ABC"; int size = 5; char padChar = '0'; System.out.println(StringUtils.leftPad(str, size, padChar)); // 00ABC System.out.println(StringUtils.rightPad(str, size, padChar)); // ABC00 } } |
3. Using Guava
You can also leverage padStart() and padEnd() method offered by Guava’s Strings class. The method signature remains the same as the above solution.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import com.google.common.base.Strings; public class Main { public static void main(String[] args) { String str = "ABC"; int size = 5; char padChar = '0'; System.out.println(Strings.padStart(str, size, padChar)); // 00ABC System.out.println(Strings.padEnd(str, size, padChar)); // ABC00 } } |
That’s all about padding a String 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 :)