Java - truncate string from left with formatter flag

前端 未结 3 887
半阙折子戏
半阙折子戏 2020-12-11 15:34

I have a string, say:

String s = \"0123456789\";

I want to pad it with a formatter. I can do this two ways:

String.format(\         


        
3条回答
  •  无人及你
    2020-12-11 15:47

    The - flag is for justification and doesn't seem to have anything to do with truncation.

    The . is used for "precision", which apparently translates to truncation for string arguments.

    I don't think format strings supports truncating from the left. You'll have to resort to

    String.format("[%.5s]", s.length() > 5 ? s.substring(s.length()-5) : s);
    

提交回复
热议问题