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

前端 未结 3 2026
醉梦人生
醉梦人生 2020-12-08 18:05

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

相关标签:
3条回答
  • 2020-12-08 18:49
    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.

    0 讨论(0)
  • 2020-12-08 19:06

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

    0 讨论(0)
  • 2020-12-08 19:10

    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
    
    0 讨论(0)
提交回复
热议问题