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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:01:56  来源:igfitidea点击:

How to create String of length consisting of same character repeated multiple times?

java

提问by James Raitsev

If i want a String swhich would consist of ninstances of character A, can this be done cleaner in Java other then

如果我想要一个String sn字符实例组成的字符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: StringUtilsis not built-in to the JDK - see http://commons.apache.org/proper/commons-lang/

注意:StringUtils不是 JDK 内置的 - 请参阅http://commons.apache.org/proper/commons-lang/