https://mkyong.com/java/how-to-pad-a-string-in-java/html
This article shows you how to use the JDK1.5 String.format()
and Apache Common Lang
to left or right pad a String in Java.java
By default, the String.format()
fills extra with spaces \u0020
. Normally, we use replace()
to pad with other chars, but it will replace the spaces in between the given string.apache
package com.mkyong; public class JavaPadString1 { public static void main(String[] args) { String input = "I Love Java!"; // I Love Java! String result1 = String.format("%s", input); // pad 20 chars String result2 = String.format("|%20s|", input); // | I Love Java!| String result3 = String.format("|%-20s|", input); // |I Love Java! | // ********I*Love*Java! String result4 = String.format("%20s", input).replace(" ", "*"); // I*Love*Java!******** String result5 = String.format("%-20s", input).replace(" ", "*"); System.out.println(result1); System.out.println(result2); System.out.println(result3); System.out.println(result4); System.out.println(result5); } }
Outputapi
I Love Java! | I Love Java!| |I Love Java! | ********I*Love*Java! I*Love*Java!********
To solve the String.format
issue above, we can use Apache Common Lang
to left, right or center pad a String.bash
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
package com.mkyong; import org.apache.commons.lang3.StringUtils; public class JavaPadString2 { public static void main(String[] args) { String input = "I Love Java!"; String result4 = StringUtils.leftPad(input, 20, "*"); String result5 = StringUtils.rightPad(input, 20, "*"); String result6 = StringUtils.center(input, 20, "*"); System.out.println(result4); System.out.println(result5); System.out.println(result6); } }
Outputoracle
********I Love Java! I Love Java!******** ****I Love Java!****
If you don’t want to include a library to pad a String, dig into the Apache Common Lang StringUtils.leftPad
, and copy the source code 🙂post
public static String leftPad(final String str, final int size, String padStr) { if (str == null) { return null; } if (isEmpty(padStr)) { padStr = SPACE; } final int padLen = padStr.length(); final int strLen = str.length(); final int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return leftPad(str, size, padStr.charAt(0)); } if (pads == padLen) { return padStr.concat(str); } else if (pads < padLen) { return padStr.substring(0, pads).concat(str); } else { final char[] padding = new char[pads]; final char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return new String(padding).concat(str); } }
P.S Above is the source code of StringUtils.leftPad
, from Apache Common Lang.spa