問題描述
我需要生成固定長度的字符串來生成基于字符位置的文件.缺少的字符必須用空格字符填充.
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?
這篇關于生成用空格填充的固定長度字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!