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

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?

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)