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


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 29-Jun-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements