Java - 创建一个具有指定长度并填充特定字符的新String实例。最佳方案? [英] Java - Create a new String instance with specified length and filled with specific character. Best solution?

查看:1470
本文介绍了Java - 创建一个具有指定长度并填充特定字符的新String实例。最佳方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实检查了其他问题;这个问题的重点是以最有效的方式解决这个特定问题。

I did check the other questions; this question has its focus on solving this particular question the most efficient way.

有时您想要创建一个具有指定长度的新字符串,并使用填充整个字符串的默认字符。

Sometimes you want to create a new string with a specified length, and with a default character filling the entire string.

也就是说,如果你能做 new String(10,'*')并从那里创建一个新的字符串会很酷,长度为10个字符全部有一个*。

ie, it would be cool if you could do new String(10, '*') and create a new String from there, with a length of 10 characters all having a *.

因为这样的构造函数不存在,并且你不能从String扩展,你要么创建一个包装类或一个方法来为你做这个。

Because such a constructor does not exist, and you cannot extend from String, you have either to create a wrapper class or a method to do this for you.

此时我正在使用此:

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更快。

It still lacks any checking (ie, when length is 0 it will not work). I am constructing the array first because I believe it is faster than using string concatination or using a StringBuffer to do so.

其他人有更好的解决方案吗?

Anyone else has a better sollution?

推荐答案

Apache Commons Lang(可能对任何非平凡项目的类路径都有用) StringUtils .repeat()

Apache Commons Lang (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():

String filled = StringUtils.repeat("*", 10);

简单!

这篇关于Java - 创建一个具有指定长度并填充特定字符的新String实例。最佳方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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