使用java.lang.String.format()填充具有给定字符的字符串
我有一个字符串,我想用任何给定的字符将这个字符串填充到给定的长度。 当然,我可以写一个循环语句并完成工作,但这不是我想要的 我使用的一种方法是使用java.lang.String.format()填充具有给定字符的字符串,java,string,string.format,Java,String,String.format,我有一个字符串,我想用任何给定的字符将这个字符串填充到给定的长度。 当然,我可以写一个循环语句并完成工作,但这不是我想要的 我使用的一种方法是 myString = String.format("%1$"+ n + "s", myString).replace(' ', newChar); 除非myString中已经有一个空格,否则它可以正常工作。是否有更好的解决方案使用String.format()您可以尝试使用Commons StringUtils或方法,如下所示 StringUtils.
myString = String.format("%1$"+ n + "s", myString).replace(' ', newChar);
除非myString
中已经有一个空格,否则它可以正常工作。是否有更好的解决方案使用String.format()您可以尝试使用Commons StringUtils或方法,如下所示
StringUtils.leftPad("test", 8, 'z');
产出
ZZZT测试
如果字符串不包含“0”符号,则可以执行以下操作:
int n = 30; // assert that n > test.length()
char newChar = 'Z';
String test = "string with no zeroes";
String result = String.format("%0" + (n - test.length()) + "d%s", 0, test)
.replace('0', newChar);
// ZZZZZZZZZstring with no zeroes
或者如果有:
test = "string with 0 00";
result = String.format("%0" + (n - test.length()) + "d", 0).replace('0', newChar)
+ test;
// ZZZZZZZZZZZZZZstring with 0 00
// or equivalently:
result = String.format("%" + (n - test.length()) + "s", ' ').replace(' ', newChar)
+ test;