StringUtils.repeat函数赏析与疑问

     今天实现一个字符串拼接的一个需求,比如:
      
输入:
 int times = 3;
String str = "abcd";
输出:
abcdabcdabcd
    
    本身想自己用StringBuffer写的,后来稍微查了下,发现org.apache.commons.lang.StringUtils.repeat实现了,稍微看了下它的实现,感觉这个库的作者实现的比我们想象的严禁多了。
    下来我们看下:
   
 public static String repeat(String str, int repeat) {
        // Performance tuned for 2.0 (JDK1.4)

        if (str == null ) {
            return null ;
        }
        if (repeat <= 0) {
            return EMPTY ;
        }
        int inputLength = str.length();
        if (repeat == 1 || inputLength == 0) {
            return str;
        }
        if (inputLength == 1 && repeat <= PAD_LIMIT) {
            return padding(repeat, str.charAt(0));
        }

        int outputLength = inputLength * repeat;
        switch (inputLength) {
            case 1 :
                char ch = str.charAt(0);
                char [] output1 = new char[outputLength];
                for (int i = repeat - 1; i >= 0; i--) {
                    output1[i] = ch;
                }
                return new String(output1);
            case 2 :
                char ch0 = str.charAt(0);
                char ch1 = str.charAt(1);
                char [] output2 = new char[outputLength];
                for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                    output2[i] = ch0;
                    output2[i + 1] = ch1;
                }
                return new String(output2);
            default :
                StringBuffer buf = new StringBuffer(outputLength);
                for (int i = 0; i < repeat; i++) {
                    buf.append(str);
                }
                return buf.toString();
        }
    }
 
实现的亮点我来稍微总结下
  • 开头的时候就进行了参数的校验,这个里面我个人的感觉,如果repeat为0的时候,应该返回原字符串,为什么要返回empty?
  • 这个里面如果是单个字符repeat的话,会判断repeat次数和PAD_LIMIT的关系,PAD_LIMIT为8192,这个我就有点不大明白
  • 后面就进行了判断,如果是一个字符的话,构建char数组,这个比较好理解
  • 如果是两个字符的话,这个地方少循环了一次,我感觉我写程序的话,这块考虑不到
  • 最后使用StringBuffer,这点和我想到的一致
 
 最后总结下,看这些程序确实能提高自己的认知和考虑问题的周到性。
 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值