我确实检查了其他问题;这个问题的重点是以最有效的方式解决这个特定的问题。
有时,您希望创建具有指定长度的新字符串,并使用默认字符填充整个字符串。
也就是说,如果你可以做new String(10, '*')
,并从那里创建一个新的字符串,长度为10个字符,都有一个*,那就太酷了。
因为这样的构造函数不存在,并且您不能从String扩展,所以您必须创建一个包装器类或一个方法来为您完成此操作。
此时此刻,我使用的是:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
char[] array = new char[length];
int pos = 0;
while (pos < length) {
array[pos] = charToFill;
pos++;
}
return new String(array);
}
它仍然缺少任何检查(例如,当长度为0时,它将不起作用)。我首先构造数组,因为我认为它比使用字符串连接或使用StringBuffer更快。
还有谁有更好的解决方案?
发布于 2009-11-26 18:47:53
Apache Commons Lang (可能非常有用,可以放在任何重要项目的类路径中)具有StringUtils.repeat()
String filled = StringUtils.repeat("*", 10);
简单!
发布于 2009-11-26 18:42:53
只需使用apache commons lang项目中的StringUtils类。您有一个leftPad方法:
StringUtils.leftPad("foobar", 10, '*'); // Returns "****foobar"
发布于 2009-11-26 18:43:44
不需要执行循环,只使用标准Java库类:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
if (length > 0) {
char[] array = new char[length];
Arrays.fill(array, charToFill);
return new String(array);
}
return "";
}
如您所见,我还为length == 0
添加了适当的代码。
https://stackoverflow.com/questions/1802915
复制相似问题