How can I left-align strings using String.format()?
Asked Answered
H

3

65

I'm using String.format() in Java trying to emulate the printf() control channel available in C. I understand how to specify that a string should be placed in a field which takes 20 characters, 5, 2 ... with 3 decimals, 2, etc. However, the strings are printed right-aligned in their field.

How do I left-align the strings?

Here's an example of a possible output which I would like to modify to left-align EXECUTING and CREATED in their fields.

Process PID: 25    Status: -----------       EXECUTING
Process PID: 36    Status: READY-SUSPENDED
Process PID:  4    Status: ----------------        CREATED

*note: consider '-' as an empty space

Hobnob answered 4/2, 2011 at 0:21 Comment(0)
M
117

Same way as with printf -- use a - modifier in the format

Millan answered 4/2, 2011 at 0:23 Comment(2)
And if you're using the position specifier, String.format("%1$-10s", "test")Amesace
Can you include an example in your answer?Saskatchewan
C
9
System.out.format("%-10d%-32s%-16s%-16s%-32s", obj.getId(), obj.getBname(), obj.getAname(),obj.getLanguage(),obj.getPublication());

Just add hyphen - in front of the number.

Constipate answered 29/7, 2020 at 12:52 Comment(0)
T
0

Like this?

class F { 
  public static void main( String ... args ) { 
    String [] status =  { "EXECUTING", "READY-SUSPENDED", "CREATED" };
    int [] pids =  {123, 34, 1231 };
    int i = 0;
    for( String s : status ) { 
       System.out.printf("Process PID: %5d Status : %s%n", pids[i++], s);
    }  
  }
}

Output:

$java F
Process PID:   123 Status : EXECUTING
Process PID:    34 Status : READY-SUSPENDED
Process PID:  1231 Status : CREATED
Typhoeus answered 4/2, 2011 at 1:4 Comment(2)
This isn't left justified, though. That requires the use of the '-'.Tumult
System.out.printf("Process PID: %5d Status : %s\n", pids[i++], s);Autarky

© 2022 - 2024 — McMap. All rights reserved.