生成用空格填充的固定长度字符串

2022-01-12 00:00:00 string formatting java

我需要生成固定长度的字符串来生成基于字符位置的文件.缺少的字符必须用空格字符填充.

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

例如,CITY 字段的固定长度为 15 个字符.对于输入芝加哥"和里约热内卢",输出是

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"

.

推荐答案

从Java 1.5开始我们可以使用方法java.lang.String.format(String, Object...) 并使用类似 printf 的格式.

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

格式字符串 "%1$15s" 完成这项工作.其中1$表示参数索引,s表示参数是String,15表示String的最小宽度.把它们放在一起:"%1$15s".

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?

相关文章