如何在 Java 中填充字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/388461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pad a String in Java?
提问by pvgoddijn
Is there some easy way to pad Strings in Java?
有没有一些简单的方法可以在 Java 中填充字符串?
Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.
似乎应该在一些类似 StringUtil 的 API 中,但我找不到任何可以做到这一点的东西。
采纳答案by GaryF
Apache StringUtils
has several methods: leftPad
, rightPad
, center
and repeat
.
阿帕奇StringUtils
有几种方法:leftPad
,rightPad
,center
和repeat
。
But please note that — as others have mentioned and demonstrated in this answer— String.format()
and the Formatter
classes in the JDK are better options. Use them over the commons code.
但请注意-如其他人所说的,并证明了这个答案-String.format()
和Formatter
JDK中的类是更好的选择。在公共代码上使用它们。
回答by Miserable Variable
Besides Apache Commons, also see String.format
which should be able to take care of simple padding (e.g. with spaces).
除了 Apache Commons,还要看看String.format
哪些应该能够处理简单的填充(例如空格)。
回答by Arne Burmeister
Have a look at org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)
.
看看org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar)
。
But the algorithm is very simple (pad right up to size chars):
但是算法非常简单(填充到大小字符):
public String pad(String str, int size, char padChar)
{
StringBuffer padded = new StringBuffer(str);
while (padded.length() < size)
{
padded.append(padChar);
}
return padded.toString();
}
回答by joel.neely
You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:
您可以通过保留填充数据来减少每次调用的开销,而不是每次都重建它:
public class RightPadder {
private int length;
private String padding;
public RightPadder(int length, String pad) {
this.length = length;
StringBuilder sb = new StringBuilder(pad);
while (sb.length() < length) {
sb.append(sb);
}
padding = sb.toString();
}
public String pad(String s) {
return (s.length() < length ? s + padding : s).substring(0, length);
}
}
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.
作为替代方法,您可以将结果长度作为pad(...)
方法的参数。在这种情况下,在该方法中而不是在构造函数中调整隐藏填充。
(Hint: For extra credit, make it thread-safe! ;-)
(提示:为了额外的功劳,让它线程安全!;-)
回答by Tom Hawtin - tackline
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).
java.util.Formatter
将做左右填充。不需要奇怪的第三方依赖项(您是否想为如此微不足道的东西添加它们)。
[I've left out the details and made this post 'community wiki' as it is not something I have a need for.]
[我忽略了细节并将这篇文章称为“社区维基”,因为它不是我需要的东西。]
回答by RealHowTo
Since Java 1.5, String.format()
can be used to left/right pad a given string.
从 Java 1.5 开始,String.format()
可用于左/右填充给定的字符串。
public static String padRight(String s, int n) {
return String.format("%-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%" + n + "s", s);
}
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 20) + "*");
}
And the output is:
输出是:
Howto *
Howto*
回答by ef_oren
you can use the built in StringBuilder append() and insert() methods, for padding of variable string lengths:
您可以使用内置的 StringBuilder append() 和 insert() 方法来填充可变字符串长度:
AbstractStringBuilder append(CharSequence s, int start, int end) ;
For Example:
例如:
private static final String MAX_STRING = " "; //20 spaces
Set<StringBuilder> set= new HashSet<StringBuilder>();
set.add(new StringBuilder("12345678"));
set.add(new StringBuilder("123456789"));
set.add(new StringBuilder("1234567811"));
set.add(new StringBuilder("12345678123"));
set.add(new StringBuilder("1234567812234"));
set.add(new StringBuilder("1234567812222"));
set.add(new StringBuilder("12345678122334"));
for(StringBuilder padMe: set)
padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());
回答by ck.
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.
我知道这个线程有点老,最初的问题是为了一个简单的解决方案,但如果它应该非常快,你应该使用一个字符数组。
public static String pad(String str, int size, char padChar)
{
if (str.length() < size)
{
char[] temp = new char[size];
int i = 0;
while (i < str.length())
{
temp[i] = str.charAt(i);
i++;
}
while (i < size)
{
temp[i] = padChar;
i++;
}
str = new String(temp);
}
return str;
}
the formatter solution is not optimal. just building the format string creates 2 new strings.
格式化程序解决方案不是最佳的。只需构建格式字符串即可创建 2 个新字符串。
apache's solution can be improved by initializing the sb with the target size so replacing below
可以通过使用目标大小初始化 sb 来改进 apache 的解决方案,因此在下面替换
StringBuffer padded = new StringBuffer(str);
with
和
StringBuffer padded = new StringBuffer(pad);
padded.append(value);
would prevent the sb's internal buffer from growing.
会阻止某人的内部缓冲区增长。
回答by Nthalk
This took me a little while to figure out. The real key is to read that Formatter documentation.
这花了我一点时间才弄明白。真正的关键是阅读格式化程序文档。
// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
// See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
// Format: %[argument_index$][flags][width]conversion
// Conversion: 'x', 'X' integral The result is formatted as a hexadecimal integer
"%1x",
digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);
回答by Sebastian S.
This works:
这有效:
"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")
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...
它将用空格填充最多 9 个字符的 String XXX。之后,所有空格都将替换为 0。您可以将空格和 0 更改为您想要的任何内容...