如何创建长度由多次重复相同字符组成的字符串? [英] How to create String of length consisting of same character repeated multiple times?

查看:151
本文介绍了如何创建长度由多次重复相同字符组成的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要字符串s ,其中包含 n 字符实例 A ,这可以在Java中更清洁吗

If i want a String s which would consist of n instances of character A, can this be done cleaner in Java other then

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.

推荐答案

这个代码完全没有错......但也许你可以使用数组.fill()

Nothing wrong with this code at all... But maybe you can use Arrays.fill():

public static String stringOfSize(int size, char ch)
{
    final char[] array = new char[size];
    Arrays.fill(array, ch);
    return new String(array);
}

这篇关于如何创建长度由多次重复相同字符组成的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆