[java] How can I pad a String in Java?

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.

This question is related to java string padding

The answer is


Padding to 10 characters:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

output:

  *******foo
  bar*******
  longer*than*10*chars

Display '*' for characters of password:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

output has the same length as the password string:

  secret123
  *********

How is this

String is "hello" and required padding is 15 with "0" left pad

String ax="Hello";
while(ax.length() < 15) ax="0"+ax;

i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.

public static String pad(String str, int size, char padChar)
{
    if (str.length() < size)
    {
        char[] temp = new char[size];
        int i = 0;

        while (i < str.length())
        {
            temp[i] = str.charAt(i);
            i++;
        }

        while (i < size)
        {
            temp[i] = padChar;
            i++;
        }

        str = new String(temp);
    }

    return str;
}

the formatter solution is not optimal. just building the format string creates 2 new strings.

apache's solution can be improved by initializing the sb with the target size so replacing below

StringBuffer padded = new StringBuffer(str); 

with

StringBuffer padded = new StringBuffer(pad); 
padded.append(value);

would prevent the sb's internal buffer from growing.


A lot of people have some very interesting techniques but I like to keep it simple so I go with this :

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}

All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.

public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
    if (pStringChar.length < pTotalLength) {
        char[] retChar = new char[pTotalLength];
        int padIdx = pTotalLength - pStringChar.length;
        Arrays.fill(retChar, 0, padIdx, pPad);
        System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
        return retChar;
    } else {
        return pStringChar;
    }
}
  • note it is called with String.toCharArray() and the result can be converted to String with new String((char[])result). The reason for this is, if you applying multiple operations you can do them all on char[] and not keep on converting between formats - behind the scenes, String is stored as char[]. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)


public static String LPad(String str, Integer length, char car) {
  return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
}

public static String RPad(String str, Integer length, char car) {
  return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
}

LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
RPad("Hi", 10, ' ') //gives "Hi        "
RPad("Hi", 1, ' ')  //gives "H"
//etc...

you can use the built in StringBuilder append() and insert() methods, for padding of variable string lengths:

AbstractStringBuilder append(CharSequence s, int start, int end) ;

For Example:

private static final String  MAX_STRING = "                    "; //20 spaces

    Set<StringBuilder> set= new HashSet<StringBuilder>();
    set.add(new StringBuilder("12345678"));
    set.add(new StringBuilder("123456789"));
    set.add(new StringBuilder("1234567811"));
    set.add(new StringBuilder("12345678123"));
    set.add(new StringBuilder("1234567812234"));
    set.add(new StringBuilder("1234567812222"));
    set.add(new StringBuilder("12345678122334"));

    for(StringBuilder padMe: set)
        padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());

Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

But the algorithm is very simple (pad right up to size chars):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}

In Guava, this is easy:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');

Java oneliners, no fancy library.

// 6 characters padding example
String pad = "******";
// testcases for 0, 4, 8 characters
String input = "" | "abcd" | "abcdefgh"

Pad Left, don't limit

result = pad.substring(Math.min(input.length(),pad.length())) + input;
results: "******" | "**abcd" | "abcdefgh"

Pad Right, don't limit

result = input + pad.substring(Math.min(input.length(),pad.length()));
results: "******" | "abcd**" | "abcdefgh"

Pad Left, limit to pad length

result = (pad + input).substring(input.length(), input.length() + pad.length());
results: "******" | "**abcd" | "cdefgh"

Pad Right, limit to pad length

result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"

Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

But the algorithm is very simple (pad right up to size chars):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)


This works:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...


This took me a little while to figure out. The real key is to read that Formatter documentation.

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);

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*

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).


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*

java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]


Java oneliners, no fancy library.

// 6 characters padding example
String pad = "******";
// testcases for 0, 4, 8 characters
String input = "" | "abcd" | "abcdefgh"

Pad Left, don't limit

result = pad.substring(Math.min(input.length(),pad.length())) + input;
results: "******" | "**abcd" | "abcdefgh"

Pad Right, don't limit

result = input + pad.substring(Math.min(input.length(),pad.length()));
results: "******" | "abcd**" | "abcdefgh"

Pad Left, limit to pad length

result = (pad + input).substring(input.length(), input.length() + pad.length());
results: "******" | "**abcd" | "cdefgh"

Pad Right, limit to pad length

result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).


In Guava, this is easy:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');

How about using recursion? Solution given below is compatible with all JDK versions and no external libraries required :)

private static String addPadding(final String str, final int desiredLength, final String padBy) {
        String result = str;
        if (str.length() >= desiredLength) {
            return result;
        } else {
            result += padBy;
            return addPadding(result, desiredLength, padBy);
        }
    }

NOTE: This solution will append the padding, with a little tweak you can prefix the pad value.


Found this on Dzone

Pad with zeros:

String.format("|%020d|", 93); // prints: |00000000000000000093|

A simple solution without any API will be as follows:

public String pad(String num, int len){
    if(len-num.length() <=0) return num;
    StringBuffer sb = new StringBuffer();
    for(i=0; i<(len-num.length()); i++){
        sb.append("0");
    }
    sb.append(num);
    return sb.toString();
}

Something simple:

The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

Substring start from the value length char index until end length of padded:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

More precise

pad right:

String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"

pad left:

String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"

Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

But the algorithm is very simple (pad right up to size chars):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}

Something simple:

The value should be a string. convert it to string, if it's not. Like "" + 123 or Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

Substring start from the value length char index until end length of padded:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

More precise

pad right:

String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"

pad left:

String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"

How is this

String is "hello" and required padding is 15 with "0" left pad

String ax="Hello";
while(ax.length() < 15) ax="0"+ax;

Use this function.

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

how to use?

leftPadding(month, 2, '0');

output: 01 02 03 04 .. 11 12


Padding to 10 characters:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

output:

  *******foo
  bar*******
  longer*than*10*chars

Display '*' for characters of password:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

output has the same length as the password string:

  secret123
  *********

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*

Since Java 11, String.repeat(int) can be used to left/right pad a given string.

System.out.println("*".repeat(5)+"apple");
System.out.println("apple"+"*".repeat(5));

Output:

*****apple
apple*****

Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.

The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:

StringUtils.defaultString(StringUtils.leftPad(myString, 1))

Explain:

  • myString: the string I input, can be null
  • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too
  • then use defaultString to give empty string to prevent concatenate null

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)


Here's a parallel version for those of you that have very long Strings :-)

int width = 100;
String s = "129018";

CharSequence padded = IntStream.range(0,width)
            .parallel()
            .map(i->i-(width-s.length()))
            .map(i->i<0 ? '0' :s.charAt(i))
            .collect(StringBuilder::new, (sb,c)-> sb.append((char)c), (sb1,sb2)->sb1.append(sb2));

This took me a little while to figure out. The real key is to read that Formatter documentation.

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);

A simple solution would be:

package nl;
public class Padder {
    public static void main(String[] args) {
        String s = "123" ;
        System.out.println("#"+("     " + s).substring(s.length())+"#");
    }
}

Here is another way to pad to the right:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";

A lot of people have some very interesting techniques but I like to keep it simple so I go with this :

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}

This utility class that is useful for left pad and zero fill of Strings. I hope that it helps someone!

package your.package.name;

/**
 * Utility class for left pad and zero fill of Strings.
 * 
 */
public class LeftPad {

    public static String lpad(String string, int length, char fill) {
        return new String(lpad(string.toCharArray(), length, fill));
    }

    public static String zerofill(String string, int length) {
        return new String(zerofill(string.toCharArray(), length));
    }

    private static char[] lpad(char[] chars, int length, char fill) {

        int delta = 0;
        int limit = 0;

        if (length > chars.length) {
            delta = length - chars.length;
            limit = length;
        } else {
            delta = 0;
            limit = chars.length;
        }

        char[] output = new char[chars.length + delta];
        for (int i = 0; i < limit; i++) {
            if (i < delta) {
                output[i] = fill;
            } else {
                output[i] = chars[i - delta];
            }
        }
        return output;
    }

    private static char[] zerofill(char[] chars, int length) {
        return lpad(chars, length, '0');
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "123";
        char pad = ' ';

        System.out.println("left pad blank: " + string);
        System.out.println("Result: [" + LeftPad.lpad(string, 10, pad) + "]");

        System.out.println();
        System.out.println("zero fill: " + string);
        System.out.println("Result: [" + LeftPad.zerofill(string, 10) + "]");
    }
}

This is the output:

left pad blank: 123
Result: [       123]

zero fill: 123
Result: [0000000123]

You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

As an alternative, you can make the result length a parameter to the pad(...) method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.

(Hint: For extra credit, make it thread-safe! ;-)


i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.

public static String pad(String str, int size, char padChar)
{
    if (str.length() < size)
    {
        char[] temp = new char[size];
        int i = 0;

        while (i < str.length())
        {
            temp[i] = str.charAt(i);
            i++;
        }

        while (i < size)
        {
            temp[i] = padChar;
            i++;
        }

        str = new String(temp);
    }

    return str;
}

the formatter solution is not optimal. just building the format string creates 2 new strings.

apache's solution can be improved by initializing the sb with the target size so replacing below

StringBuffer padded = new StringBuffer(str); 

with

StringBuffer padded = new StringBuffer(pad); 
padded.append(value);

would prevent the sb's internal buffer from growing.


public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}

A simple solution would be:

package nl;
public class Padder {
    public static void main(String[] args) {
        String s = "123" ;
        System.out.println("#"+("     " + s).substring(s.length())+"#");
    }
}

@ck's and @Marlon Tarak's answers are the only ones to use a char[], which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.

public static String pad(String source, char fill, int length, boolean right){
    if(source.length() > length) return source;
    char[] out = new char[length];
    if(right){
        System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
        Arrays.fill(out, source.length(), length, fill);
    }else{
        int sourceOffset = length - source.length();
        System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
        Arrays.fill(out, 0, sourceOffset, fill);
    }
    return new String(out);
}

Simple test method:

public static void main(String... args){
    System.out.println("012345678901234567890123456789");
    System.out.println(pad("cats", ' ', 30, true));
    System.out.println(pad("cats", ' ', 30, false));
    System.out.println(pad("cats", ' ', 20, false));
    System.out.println(pad("cats", '$', 30, true));
    System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}

Outputs:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy 

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).


This utility class that is useful for left pad and zero fill of Strings. I hope that it helps someone!

package your.package.name;

/**
 * Utility class for left pad and zero fill of Strings.
 * 
 */
public class LeftPad {

    public static String lpad(String string, int length, char fill) {
        return new String(lpad(string.toCharArray(), length, fill));
    }

    public static String zerofill(String string, int length) {
        return new String(zerofill(string.toCharArray(), length));
    }

    private static char[] lpad(char[] chars, int length, char fill) {

        int delta = 0;
        int limit = 0;

        if (length > chars.length) {
            delta = length - chars.length;
            limit = length;
        } else {
            delta = 0;
            limit = chars.length;
        }

        char[] output = new char[chars.length + delta];
        for (int i = 0; i < limit; i++) {
            if (i < delta) {
                output[i] = fill;
            } else {
                output[i] = chars[i - delta];
            }
        }
        return output;
    }

    private static char[] zerofill(char[] chars, int length) {
        return lpad(chars, length, '0');
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "123";
        char pad = ' ';

        System.out.println("left pad blank: " + string);
        System.out.println("Result: [" + LeftPad.lpad(string, 10, pad) + "]");

        System.out.println();
        System.out.println("zero fill: " + string);
        System.out.println("Result: [" + LeftPad.zerofill(string, 10) + "]");
    }
}

This is the output:

left pad blank: 123
Result: [       123]

zero fill: 123
Result: [0000000123]

java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]


Here is another way to pad to the right:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";

Since Java 11, String.repeat(int) can be used to left/right pad a given string.

System.out.println("*".repeat(5)+"apple");
System.out.println("apple"+"*".repeat(5));

Output:

*****apple
apple*****

public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}

java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]


All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.

public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
    if (pStringChar.length < pTotalLength) {
        char[] retChar = new char[pTotalLength];
        int padIdx = pTotalLength - pStringChar.length;
        Arrays.fill(retChar, 0, padIdx, pPad);
        System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
        return retChar;
    } else {
        return pStringChar;
    }
}
  • note it is called with String.toCharArray() and the result can be converted to String with new String((char[])result). The reason for this is, if you applying multiple operations you can do them all on char[] and not keep on converting between formats - behind the scenes, String is stored as char[]. If these operations were included in the String class itself, it would have been twice as efficient - speed and memory wise.

Found this on Dzone

Pad with zeros:

String.format("|%020d|", 93); // prints: |00000000000000000093|

public static String LPad(String str, Integer length, char car) {
  return (str + String.format("%" + length + "s", "").replace(" ", String.valueOf(car))).substring(0, length);
}

public static String RPad(String str, Integer length, char car) {
  return (String.format("%" + length + "s", "").replace(" ", String.valueOf(car)) + str).substring(str.length(), length + str.length());
}

LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
RPad("Hi", 10, ' ') //gives "Hi        "
RPad("Hi", 1, ' ')  //gives "H"
//etc...

Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.

The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:

StringUtils.defaultString(StringUtils.leftPad(myString, 1))

Explain:

  • myString: the string I input, can be null
  • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too
  • then use defaultString to give empty string to prevent concatenate null

Here's a parallel version for those of you that have very long Strings :-)

int width = 100;
String s = "129018";

CharSequence padded = IntStream.range(0,width)
            .parallel()
            .map(i->i-(width-s.length()))
            .map(i->i<0 ? '0' :s.charAt(i))
            .collect(StringBuilder::new, (sb,c)-> sb.append((char)c), (sb1,sb2)->sb1.append(sb2));

Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

But the algorithm is very simple (pad right up to size chars):

public String pad(String str, int size, char padChar)
{
  StringBuilder padded = new StringBuilder(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}

@ck's and @Marlon Tarak's answers are the only ones to use a char[], which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.

public static String pad(String source, char fill, int length, boolean right){
    if(source.length() > length) return source;
    char[] out = new char[length];
    if(right){
        System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
        Arrays.fill(out, source.length(), length, fill);
    }else{
        int sourceOffset = length - source.length();
        System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
        Arrays.fill(out, 0, sourceOffset, fill);
    }
    return new String(out);
}

Simple test method:

public static void main(String... args){
    System.out.println("012345678901234567890123456789");
    System.out.println(pad("cats", ' ', 30, true));
    System.out.println(pad("cats", ' ', 30, false));
    System.out.println(pad("cats", ' ', 20, false));
    System.out.println(pad("cats", '$', 30, true));
    System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}

Outputs:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy 

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).


This works:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...


How about using recursion? Solution given below is compatible with all JDK versions and no external libraries required :)

private static String addPadding(final String str, final int desiredLength, final String padBy) {
        String result = str;
        if (str.length() >= desiredLength) {
            return result;
        } else {
            result += padBy;
            return addPadding(result, desiredLength, padBy);
        }
    }

NOTE: This solution will append the padding, with a little tweak you can prefix the pad value.


java.util.Formatter will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).

[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]


Use this function.

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

how to use?

leftPadding(month, 2, '0');

output: 01 02 03 04 .. 11 12


you can use the built in StringBuilder append() and insert() methods, for padding of variable string lengths:

AbstractStringBuilder append(CharSequence s, int start, int end) ;

For Example:

private static final String  MAX_STRING = "                    "; //20 spaces

    Set<StringBuilder> set= new HashSet<StringBuilder>();
    set.add(new StringBuilder("12345678"));
    set.add(new StringBuilder("123456789"));
    set.add(new StringBuilder("1234567811"));
    set.add(new StringBuilder("12345678123"));
    set.add(new StringBuilder("1234567812234"));
    set.add(new StringBuilder("1234567812222"));
    set.add(new StringBuilder("12345678122334"));

    for(StringBuilder padMe: set)
        padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());

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*

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to padding

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Adding space/padding to a UILabel How to adjust gutter in Bootstrap 3 grid system? Why is there an unexplainable gap between these inline-block div elements? How to increase the distance between table columns in HTML? Absolute positioning ignoring padding of parent Remove all padding and margin table HTML and CSS Style the first <td> column of a table differently Using margin / padding to space <span> from the rest of the <p>