JavaDevNotes.com

Java Left Pad String Examples

Here are some example codes to pad a custom character to the left side of a String to achieve a target length.

Description

What we wish is to implement this function:

public static String leftPad(String originalString, int length, char padCharacter)

  • originalString - the String we want to append to
  • length - target length of the String
  • padCharacter - the character to padd to the left side of the String

For example, this code:

String test = leftPad("123", 5, '-')

Should have the equivalent content when this code is used:

String test = "--123";

Left Pad Custom Character Using Simple Concatenation

Here is a simple implementation of the target logic using simple String concatenation:
public class Test {
   public static void main(String[] args) {
      System.out.println(leftPad("ABC", 10, 'x'));
   }
   public static String leftPad(String originalString, int length,
         char padCharacter) {
      String paddedString = originalString;
      while (paddedString.length() < length) {
         paddedString = padCharacter + paddedString;
      }
      return paddedString;
   }
}
This will keep on adding a character to the left side of the String until the target length is achieved. Here is the sample output:
xxxxxxxABC

Left Pad Custom Character Using StringBuilder

Here is a similar implementation for left padding a character to a String. Using StringBuilder should be efficient. Here is an example code:
public class Test {
   public static void main(String[] args) {
      System.out.println(leftPad("XYZ", 10, '-'));
   }
   public static String leftPad(String originalString, int length,
         char padCharacter) {
      StringBuilder sb = new StringBuilder();
      while (sb.length() + originalString.length() < 10) {
         sb.append(padCharacter);
      }
      sb.append(originalString);
      String paddedString = sb.toString();
      return paddedString;
   }
}
And this is the sample output:
-------XYZ

Left Pad Custom Character Using Substring Trick

We can use the subtring method of a String to perform the required left padding. Here is a sample code:

public class Test {
   public static void main(String[] args) {
      System.out.println(leftPad("TEST", 10, '+'));
   }
   public static String leftPad(String originalString, int length,
         char padCharacter) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < length; i++) {
         sb.append(padCharacter);
      }
      String padding = sb.toString();
      String paddedString = padding.substring(originalString.length())
            + originalString;
      return paddedString;
   }
}

The first portion builds length (e.g. 10) number of pad characters. Then a substring is performed on it to crop out the excess padding. It is then concatenated to the target String.

Here is a sample output:

++++++TEST