Padding Strings with format method on Java

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.next();
    int x = sc.nextInt();

    PadLeft(s1);
    System.out.printf("%03d", x);
    System.out.println();

    PadRight(s1);
    System.out.printf("%03d", x);
}

private static void PadRight(String s)
{
    System.out.printf("%1$15s", s);
}

private static void PadLeft(String s)
{
    System.out.printf("%1$-15s", s);
}

15 represents the minimal width of the String

Input

Hello
12

Output

Hello          012
          Hello012

References
https://stackoverflow.com/questions/13475388/generate-fixed-length-strings-filled-with-whitespaces
http://www.rgagnon.com/javadetails/java-0448.html

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.