Languages
[Edit]
EN

Java - padding left string or number with String.format()

4 points
Created by:
Jasmin
305

In this short article, we would like to show how in Java, pad left indicated string or number using String.format() method.

Quick solution:

System.out.println(String.format("%10s", 123));     //       123
System.out.println(String.format("%13s", "abc"));   //          abc

or:

//                                                       7    +3     =  10
//                                                    vvvvvvvxxx   
System.out.println(String.format("%1$10s", 123));   //       123

//                                                        10     +3  =  13
//                                                    vvvvvvvvvvxxx
System.out.println(String.format("%1$13s", "abc")); //          abc

Where:

  • 10 and 13 represent returned minimal string size (spaces + argument) (used in %10s, %13s, %1$10s and %1$13s).
    e.g.        123 and           abc.
  • 1 indicates used argument number (used in %1$10s and %1$13s).

 

Explaination

Arguments addressing:

  1. using arguments order:
    String.format("%10s %10s %10s", a, b, c)

    Where: each %10s will print a, b and c variables in provided order using 10 characters (spaces + argument).

  2. using an indicated index:

    System.out.println(String.format("%1$10s / %2$10s / %2$10s", a, b));

    Where: %1 and %2 indicate used argument number, $10s indicates 10 characters (spaces + argument).

Practical example

We can indicate any number of the arguments addressing the same arguments multiple times in String.format() method.

public class Example {

     public static void main(String []args) {

        System.out.println(String.format("%10s", 123));   //       123
        System.out.println(String.format("%10s", "abc")); //       abc
        
        // accessing by used order
        // used: argument 1, agrument 2
        System.out.println(String.format("%10s / %10s", 5, 50));             //         5 /         50

        // accessing by indicated index
        // used: argument 1, agrument 2, argument 2
        System.out.println(String.format("%1$10s / %2$10s / %2$10s", 1, 2)); //         1 /          2 /         2
     }
}
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join