有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
当前回答
填充到10个字符:
String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');
输出:
*******foo
bar*******
longer*than*10*chars
密码字符显示“*”:
String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');
输出与密码字符串长度相同:
secret123
*********
其他回答
一个简单的解决方案是:
package nl;
public class Padder {
public static void main(String[] args) {
String s = "123" ;
System.out.println("#"+(" " + s).substring(s.length())+"#");
}
}
不管怎样,我一直在寻找一些可以填充的东西,然后我决定自己编写代码。它非常简洁,你可以很容易地从中推导出padLeft和padRight
/**
* Pads around a string, both left and right using pad as the template, aligning to the right or left as indicated.
* @param a the string to pad on both left and right
* @param pad the template to pad with, it can be of any size
* @param width the fixed width to output
* @param alignRight if true, when the input string is of odd length, adds an extra pad char to the left, so values are right aligned
* otherwise add an extra pad char to the right. When the input is of even length no extra chars will be inserted
* @return the input param a padded around.
*/
public static String padAround(String a, String pad, int width, boolean alignRight) {
if (pad.length() == 0)
throw new IllegalArgumentException("Pad cannot be an empty string!");
int delta = width - a.length();
if (delta < 1)
return a;
int half = delta / 2;
int remainder = delta % 2;
String padding = pad.repeat(((half+remainder)/pad.length()+1)); // repeating the padding to occupy all possible space
StringBuilder sb = new StringBuilder(width);
// sb.append( padding.substring(0,half + (alignRight ? 0 : remainder)));
sb.append(padding, 0, half + (alignRight ? 0 : remainder));
sb.append(a);
// sb.append( padding.substring(0,half + (alignRight ? remainder : 0)));
sb.append(padding, 0, half + (alignRight ? remainder : 0));
return sb.toString();
}
虽然它应该是相当快的,它可能会受益于使用一些韵母在这里和那里。
如此:
"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")
它会用空白填充你的字符串XXX,最多9个字符。在此之后,所有空格将被替换为0。你可以把空格和0改为任何你想要的…
在番石榴中,这很简单:
Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');
让我给一些情况下的答案,你需要给左/右填充(或前缀/后缀字符串或空格)在你连接到另一个字符串之前,你不想测试长度或任何if条件。
与所选答案相同,我更喜欢Apache Commons的StringUtils,但使用这种方式:
StringUtils.defaultString(StringUtils.leftPad(myString, 1))
解释:
myString:我输入的字符串,可以为空 stringutil的。leftPad(myString, 1):如果string为空,此语句也将返回null 然后使用defaultString给出空字符串,以防止连接null