如何在 Java 中填充字符串?
有没有一些简单的方法可以在Java中填充字符串?
似乎应该在一些类似 StringUtil 的 API 中,但我找不到任何可以做到这一点的东西。
Is there some easy way to pad Strings in Java?
Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
从 Java 1.5 开始,
String.format()
可用于左/右填充给定的字符串。输出是:
Since Java 1.5,
String.format()
can be used to left/right pad a given string.And the output is:
填充到 10 个字符:
输出:
为密码字符显示“*”:
输出与密码字符串的长度相同:
Padding to 10 characters:
output:
Display '*' for characters of password:
output has the same length as the password string:
Apache
StringUtils
有几种方法:leftPad
,rightPad
,center
和重复
。但请注意,正如其他人在这个答案中提到和演示的那样 -
String.format()
和 JDK 中的 Formatter 类是更好的选择。 在公共代码上使用它们。Apache
StringUtils
has several methods:leftPad
,rightPad
,center
andrepeat
.But please note that — as others have mentioned and demonstrated in this answer —
String.format()
and theFormatter
classes in the JDK are better options. Use them over the commons code.在 Guava 中,这很简单:
In Guava, this is easy:
简单一点:
该值应该是一个字符串。 如果不是,则将其转换为字符串。 类似于
"" + 123
或Integer.toString(123)
子字符串从值长度字符索引开始直到填充的结束长度:
更精确
pad右:
垫 左:
Something simple:
The value should be a string. convert it to string, if it's not. Like
"" + 123
orInteger.toString(123)
Substring start from the value length char index until end length of padded:
More precise
pad right:
pad left:
查看 org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar) 。
但算法非常简单(填充到大小字符):
Have a look at
org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)
.But the algorithm is very simple (pad right up to size chars):
除了 Apache Commons 之外,还请参阅
String.format
,它应该能够处理简单的填充(例如使用空格)。Besides Apache Commons, also see
String.format
which should be able to take care of simple padding (e.g. with spaces).从 Java 11 开始,String.repeat(int) 可用于左/右填充给定的字符串。
输出:
Since Java 11, String.repeat(int) can be used to left/right pad a given string.
Output:
上找到此内容:
在 Dzone Pad
Found this on Dzone
Pad with zeros:
我知道这个线程有点旧,最初的问题是为了一个简单的解决方案,但如果它应该非常快,你应该使用 char 数组。
格式化程序解决方案不是最佳的。 仅构建格式字符串就会创建 2 个新字符串。
apache 的解决方案可以通过使用目标大小初始化 sb 来改进,因此将下面的替换
为
可以防止 sb 的内部缓冲区增长。
i know this thread is kind of old and the original question was for an easy solution but if it's supposed to be really fast, you should use a char array.
the formatter solution is not optimal. just building the format string creates 2 new strings.
apache's solution can be improved by initializing the sb with the target size so replacing below
with
would prevent the sb's internal buffer from growing.
这花了我一些时间才弄清楚。
真正的关键是阅读 Formatter 文档。
This took me a little while to figure out.
The real key is to read that Formatter documentation.
这是向右填充的另一种方法:
Here is another way to pad to the right:
您可以通过保留填充数据来减少每次调用的开销,而不是每次都重建它:
作为替代方案,您可以将结果长度作为
pad(...)
方法的参数。 在这种情况下,请在该方法中而不是在构造函数中调整隐藏填充。(提示:为了获得额外的分数,请使其线程安全!;-)
You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:
As an alternative, you can make the result length a parameter to the
pad(...)
method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.(Hint: For extra credit, make it thread-safe! ;-)
@ck 和 @ Marlon Tarak 的答案是唯一使用
char[]
的答案,对于每秒多次调用填充方法的应用程序来说,这是最好的方法。 然而,它们没有利用任何数组操作优化,并且根据我的口味有点被覆盖; 这可以在完全没有循环的情况下完成。简单测试方法:
输出:
@ck's and @Marlon Tarak's answers are the only ones to use a
char[]
, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.Simple test method:
Outputs:
Java oneliners,没有花哨的库。
Pad Left,不限制
Pad Right,不限制
Pad Left,限制焊盘长度
Pad Right,限制焊盘长度
Java oneliners, no fancy library.
Pad Left, don't limit
Pad Right, don't limit
Pad Left, limit to pad length
Pad Right, limit to pad length
所有字符串操作通常都需要非常高效 - 特别是当您处理大量数据时。 我想要一些快速且灵活的东西,类似于您将在 plsql pad 命令中得到的东西。 另外,我不想为一件小事包含一个巨大的库。 考虑到这些因素,这些解决方案都不能令人满意。 这是我提出的解决方案,具有最佳的基准测试结果,如果有人可以改进它,请添加您的评论。
All string operation usually needs to be very efficient - especially if you are working with big sets of data. I wanted something that's fast and flexible, similar to what you will get in plsql pad command. Also, I don't want to include a huge lib for just one small thing. With these considerations none of these solutions were satisfactory. This is the solutions I came up with, that had the best bench-marking results, if anybody can improve on it, please add your comment.
java.util.Formatter
将进行左右填充。 不需要奇怪的第三方依赖项(您是否想为如此琐碎的事情添加它们)。[我省略了详细信息,并将这篇文章设为“社区维基”,因为它不是我需要的东西。]
java.util.Formatter
will do left and right padding. No need for odd third party dependencies (would you want to add them for something so trivial).[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]
您可以使用内置的 StringBuilder append() 和 insert() 方法,
用于填充可变字符串长度:
例如:
you can use the built in StringBuilder append() and insert() methods,
for padding of variable string lengths:
For Example:
这是有效的:
它将用空格填充您的字符串 XXX 最多 9 个字符。 之后所有空格都将替换为 0。您可以将空格和 0 更改为您想要的任何内容...
This works:
It will fill your String XXX up to 9 Chars with a whitespace. After that all Whitespaces will be replaced with a 0. You can change the whitespace and the 0 to whatever you want...
让我为某些情况留下答案,在连接到另一个字符串之前,您需要提供左/右填充(或前缀/后缀字符串或空格),并且您不想测试长度或任何 if 条件。
与所选答案相同,我更喜欢 Apache Commons 的
StringUtils
但使用这种方式:解释:
myString
:我输入的字符串,可以为 nullStringUtils .leftPad(myString, 1)
:如果字符串为 null,该语句也会返回 null,然后defaultString
给出空字符串以防止连接 nullLet's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.
The same to the selected answer, I would prefer the
StringUtils
of Apache Commons but using this way:Explain:
myString
: the string I input, can be nullStringUtils.leftPad(myString, 1)
: if string is null, this statement would return null toodefaultString
to give empty string to prevent concatenate null使用此功能。
如何使用?
输出:
01 02 03 04 .. 11 12
Use this function.
how to use?
output:
01 02 03 04 .. 11 12
很多人都有一些非常有趣的技术,但我喜欢保持简单,所以我采用以下方法:
A lot of people have some very interesting techniques but I like to keep it simple so I go with this :
这是一个高效实用程序类,用于左垫、右垫、中心垫和零填充< /strong> Java 中的字符串。
这是输出:
This is an efficient utility class for left pad, right pad, center pad and zero fill of strings in Java.
This is the output:
对于那些拥有很长字符串的人来说,这是一个并行版本:-)
Here's a parallel version for those of you that have very long Strings :-)
稍微概括一下 Eko 的答案(Java 11+):
Generalizing Eko's answer (Java 11+) a bit:
无论如何,我一直在寻找一些可以填充的东西,然后我决定自己编写代码。 它相当干净,您可以轻松地从中导出 padLeft 和 padRight
虽然它应该相当快,但它可能会从这里和那里使用一些决赛中受益。
For what it's worth, I was looking for something that would pad around and then I decided to code it myself. It's fairly clean and you can easily derive padLeft and padRight from this
While it should be fairly fast it could prolly benefit from using a few finals here and there.
为此编写自己的函数可能比其他答案更简单。
Writing your own function for this is probably simpler than other answers.
对于快速而肮脏的测试,您可以使用这个:
我发现它有用以二进制表示形式打印长值:
它打印:
For a quick and dirty test you can use this:
I found it usefull printing a long value in a binary representation:
It prints: