Java - truncate string from left with formatter flag

前端 未结 3 889
半阙折子戏
半阙折子戏 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 16:01

    I hope this is what you need:

    System.out.println("'" + String.format("%-5.5s", "") + "'");
    System.out.println("'" + String.format("%-5.5s", "123") + "'");
    System.out.println("'" + String.format("%-5.5s", "12345") + "'");
    System.out.println("'" + String.format("%-5.5s", "1234567890.....") + "'");
    

    output length is always 5:

    '     ' - filled with 5 spaces
    '123  ' filled with 2 spaces after
    '12345' - equals
    '12345' - truncated

    in addition:

    System.out.println("'" + String.format("%5.5s", "123") + "'");
    

    output:

    '  123' filled with 2 spaces before

提交回复
热议问题