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

[亡魂溺海] 提交于 2019-11-27 01:32:48

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/4893313/how-can-i-left-align-strings-using-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!