Left pad a String with a specified character in Java


The following is our string −

String str = "Amit";

Now take a StringBuilder object −

StringBuilder strBuilder = new StringBuilder();

Set the character you want to pad with a string −

Character ch = '^';

Perform left padding and extend the string length to 5 (one for the additional character). The character that will be padded comes on the left −

while (strBuilder.length() + str.length() < 5) {
strBuilder.append(ch);
}

The following is an example −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Amit";
      Character ch = '^';
      StringBuilder strBuilder = new StringBuilder();
      while (strBuilder.length() + str.length() < 5) {
         strBuilder.append(ch);
      }
      // append
      strBuilder.append(str);
      String res = strBuilder.toString();
      System.out.println(res);
   }
}

Output

^Amit

Updated on: 29-Jun-2020

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements