Left pad a String with a specified character in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 20-Dec-2018 07:49:39
Advertisements