Generate fixed length Strings filled with whitespaces

后端 未结 13 994
借酒劲吻你
借酒劲吻你 2020-12-04 13:52

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.

As an example, the fi

13条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 14:38

    Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.

    The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String. Putting it all together: "%1$15s".

    For a general method we have:

    public static String fixedLengthString(String string, int length) {
        return String.format("%1$"+length+ "s", string);
    }
    

    Maybe someone can suggest another format string to fill the empty spaces with an specific character?

提交回复
热议问题