Left pad a String with a specified String in Java


The following is our string.

String str = "Jack";

Now take a StringBuilder object.

StringBuilder strBuilder = new StringBuilder();

Perform left padding and extend the string length to 20. The string that will be padded comes on the left.

while (strBuilder.length() + str.length() < 20) {
strBuilder.append("demo");
}

The following is an example wherein we have left padded a string with another string “demo”

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Jack";
      StringBuilder strBuilder = new StringBuilder();
      // left padding with a string
      while (strBuilder.length() + str.length() < 20) {
         strBuilder.append("demo");
      }
      // append
      strBuilder.append(str);
      String res = strBuilder.toString();
      System.out.println(res);
   }
}

Output

demodemodemodemoJack

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements