有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
有一些简单的方法来填充字符串在Java?
似乎是一些应该在一些stringutil类API,但我找不到任何东西,这样做。
当前回答
public static String padLeft(String in, int size, char padChar) {
if (in.length() <= size) {
char[] temp = new char[size];
/* Llenado Array con el padChar*/
for(int i =0;i<size;i++){
temp[i]= padChar;
}
int posIniTemp = size-in.length();
for(int i=0;i<in.length();i++){
temp[posIniTemp]=in.charAt(i);
posIniTemp++;
}
return new String(temp);
}
return "";
}
其他回答
另一种利用递归的解决方案。
这与所有JDK版本兼容,不需要外部库:
private static String addPadding(final String str, final int desiredLength, final String padBy) {
String result = str;
if (str.length() >= desiredLength) {
return result;
} else {
result += padBy;
return addPadding(result, desiredLength, padBy);
}
}
注意:这个解决方案将附加填充,与一个小调整,你可以前缀填充值。
让我给一些情况下的答案,你需要给左/右填充(或前缀/后缀字符串或空格)在你连接到另一个字符串之前,你不想测试长度或任何if条件。
与所选答案相同,我更喜欢Apache Commons的StringUtils,但使用这种方式:
StringUtils.defaultString(StringUtils.leftPad(myString, 1))
解释:
myString:我输入的字符串,可以为空 stringutil的。leftPad(myString, 1):如果string为空,此语句也将返回null 然后使用defaultString给出空字符串,以防止连接null
下面是另一种向右填充的方法:
// put the number of spaces, or any character you like, in your paddedString
String paddedString = "--------------------";
String myStringToBePadded = "I like donuts";
myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());
//result:
myStringToBePadded = "I like donuts-------";
formatter会做左右填充。不需要奇怪的第三方依赖关系(您会为如此微不足道的事情添加它们吗)。
[我省略了细节,把这篇文章做成“社区维基”,因为这不是我需要的东西。]
@ck和@Marlon Tarak的答案是唯一使用char[]的答案,对于每秒有几个填充方法调用的应用程序来说,这是最好的方法。然而,它们没有利用任何数组操作优化,而且对我来说有点覆盖;这完全不需要循环。
public static String pad(String source, char fill, int length, boolean right){
if(source.length() > length) return source;
char[] out = new char[length];
if(right){
System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
Arrays.fill(out, source.length(), length, fill);
}else{
int sourceOffset = length - source.length();
System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
Arrays.fill(out, 0, sourceOffset, fill);
}
return new String(out);
}
简单测试方法:
public static void main(String... args){
System.out.println("012345678901234567890123456789");
System.out.println(pad("cats", ' ', 30, true));
System.out.println(pad("cats", ' ', 30, false));
System.out.println(pad("cats", ' ', 20, false));
System.out.println(pad("cats", '$', 30, true));
System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}
输出:
012345678901234567890123456789
cats
cats
cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy