Left pad a string in Java


To left pad a string, use the String.format and set the spaces.

String.format("|%20s|", "demotext")

If you add 30 above, it will display the first string after 30 spaces from the beginning.

String.format("|%30s|", "demotext")

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      System.out.print(String.format("|%20s|", "demotext"));
      System.out.println("Left padded!");
   }
}

Output

| demotext|Left padded

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 27-Jun-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements