`

StringUtils.repeat函数赏析与疑问

    博客分类:
  • java
阅读更多
     今天实现一个字符串拼接的一个需求,比如:
      
输入:
 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,这点和我想到的一致
 
 最后总结下,看这些程序确实能提高自己的认知和考虑问题的周到性。
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics