Limiting the number of characters in a string, and chopping off the rest

前端 未结 8 1178
故里飘歌
故里飘歌 2020-12-08 02:02

I need to create a summary table at the end of a log with some values that are obtained inside a class. The table needs to be printed in fixed-width format. I have the cod

8条回答
  •  無奈伤痛
    2020-12-08 02:29

    You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So

    System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
    

    will produce

    'abc' '  a'
    

    (you can remove quotes, obviously).

提交回复
热议问题