生成固定长度的填充空格的字符串 [英] Generate fixed length Strings filled with whitespaces

查看:569
本文介绍了生成固定长度的填充空格的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Chicago
Rio de Janeiro

从Java 1.5开始,我们可以使用 解决方案 /api/java/lang/String.html#format%28java.util.Locale,%20java.lang.String,%20java.lang.Object...%29rel =noreferrer> java.lang.String。格式字符串%1 $ 15s<格式字符串(对象...)并使用类似printf的格式。 / code>做这项工作。其中 1 $ 表示参数索引, s 表示参数是一个字符串, 15 表示String的最小宽度。
综合起来:%1 $ 15s





  public static String fixedLengthString(String string,int length){
return String.format(%1 $ + length +s,string);





$ b

也许有人可以建议另一种格式字符串来填充空白空间中的特定字符?


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"

.

解决方案

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

这篇关于生成固定长度的填充空格的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆