Rafael Borja Rafael Borja - 7 months ago 58
Java Question

Generate fixed length Strings filled with whitespaces

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 field CITY has a fixed length of 15 characters. For the inputs "Chicago" and "Rio de Janeiro" the outputs are

"        Chicago"
" Rio de Janeiro"
.

Answer

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 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?

Comments