java 如何创建由多次重复的相同字符组成的长度字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16800295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create String of length consisting of same character repeated multiple times?
提问by James Raitsev
If i want a String s
which would consist of n
instances of character A
, can this be done cleaner in Java other then
如果我想要一个String s
由n
字符实例组成的字符A
,那么可以在 Java 中更清晰地完成吗?
public static String stringOfSize(int size, char ch) {
StringBuilder s = new StringBuilder();
while (size-- > 0) {
s.append(ch);
}
return s.toString();
}
Can we do better? Just wondering.
我们能做得更好吗?就是想。
回答by fge
Nothing wrong with this code at all... But maybe you can use Arrays.fill()
:
这段代码没有任何问题......但也许你可以使用Arrays.fill()
:
public static String stringOfSize(int size, char ch)
{
final char[] array = new char[size];
Arrays.fill(array, ch);
return new String(array);
}
回答by Justin Bicknell
You could do the following:
您可以执行以下操作:
return StringUtils.repeat(ch, size);
Note: StringUtils
is not built-in to the JDK - see http://commons.apache.org/proper/commons-lang/
注意:StringUtils
不是 JDK 内置的 - 请参阅http://commons.apache.org/proper/commons-lang/