我需要生成固定长度的字符串来生成基于字符位置的文件.缺少的字符必须用空格字符填充.
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模板网!
解析 ISO 8601 字符串本地日期时间,就像在 UTC 中Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期时间,就像在 UTC 中一样)
如何将公历字符串转换为公历?How to convert Gregorian string to Gregorian Calendar?(如何将公历字符串转换为公历?)
Java:GregorianCalendar 的最大值和最小值是什么/在哪Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
1582 年 10 月 15 日之前日期的日历到日期转换.公历Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日历到日期转换
java日历setFirstDayOfWeek不起作用java Calendar setFirstDayOfWeek not working(java日历setFirstDayOfWeek不起作用)
Java:获取当前星期几的值Java: getting current Day of the Week value(Java:获取当前星期几的值)