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.
例如,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?
这篇关于生成用空格填充的固定长度字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:生成用空格填充的固定长度字符串
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
