Left pad a String with a specified String in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 17-Dec-2018 06:00:00
Advertisements