java string指定长度,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.

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 *.

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.

At this moment I am using this:

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);

}

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 (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():

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

Easy!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值