Left pad a String with spaces (' ') in Java

Java 8Object Oriented ProgrammingProgramming

Let us see an example first to understand how a string looks with left padding −

demotext //left padding with spaces
0000000demotext //left padding with 7 zeros

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. The spaces that will be padded comes on the left. Append the spaces here −

while (strBuilder.length() + str.length() < 10) {
   strBuilder.append(' ');
}

The following is an example to pad a string to the left with spaces

Example

 Live Demo

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

Output

Jack
raja
Published on 20-Dec-2018 12:24:03
Advertisements