Is there some easy way to pad Strings in Java?
Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.
String padding refers to adding, usually, non-informative characters to a string to one or both ends of it. This is most often done for output formatting and alignment purposes, but it can have useful practical applications.
leftPad() method to left pad a string with zeros, by adding leading zeros to string.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.
Since Java 1.5, String.format()
can be used to left/right pad a given string.
public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); } ... public static void main(String args[]) throws Exception { System.out.println(padRight("Howto", 20) + "*"); System.out.println(padLeft("Howto", 20) + "*"); }
And the output is:
Howto * Howto*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With