问题
java中是否有一种方法可以创建具有指定数量的指定字符的字符串?在我的例子中,我需要创建一个包含10个空格的字符串。我目前的代码是:
StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
outputBuffer.append(" ");
}
return outputBuffer.toString();
有没有更好的方法来完成同样的事情。特别是我想要一些快速的(在执行方面)。
#1 热门回答(137 赞)
可能是使用theString
API的最短代码,仅限于:
String space10 = new String(new char[10]).replace('\0', ' ');
System.out.println("[" + space10 + "]");
// prints "[ ]"
作为一种方法,无需直接实例化char
:
import java.nio.CharBuffer;
/**
* Creates a string of spaces that is 'spaces' spaces long.
*
* @param spaces The number of spaces to add to the string.
*/
public String spaces( int spaces ) {
return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}
调用使用:
System.out.printf( "[%s]%n", spaces( 10 ) );
#2 热门回答(52 赞)
嗯,现在我想起来,也许是Arrays.fill
:
char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
当然,我假设fill
方法与你的代码做同样的事情,所以它可能会执行相同的操作,但至少这是更少的行。
#3 热门回答(46 赞)
我强烈建议不要手工编写循环。你将在编程生涯中一遍又一遍地做到这一点。阅读你的代码的人 - 包括你 - 总是需要花时间,即使只是几秒钟,消化循环的意义。
而重用了个可用库,提供的代码类似于StringUtils.repeat
fromApache Commons Lang:
return StringUtils.repeat(' ', length);
这样你也不必担心性能问题,因此隐藏了StringBuilder
,编译器优化等所有血腥细节。如果函数变得很慢,那么这将是库的错误。