Guava | Strings

com.google.common.base.Strings
官方文档:Strings

Static utility methods pertaining to String or CharSequence instances. 为String和CharSequence的实例提供一些静态工具方法

1、repeat方法

/**
 * Returns a string consisting of a specific number of concatenated copies of an input string. For
 * example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}.
 *
 * @param string any non-null string
 * @param count the number of times to repeat it; a nonnegative integer
 * @return a string containing {@code string} repeated {@code count} times (the empty string if
 *     {@code count} is zero)
 * @throws IllegalArgumentException if {@code count} is negative
 */
public static String repeat(String string, int count) {
    checkNotNull(string); // eager for GWT.

    if (count <= 1) {
        checkArgument(count >= 0, "invalid count: %s", count);
        return (count == 0) ? "" : string;
    }

    // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
    final int len = string.length();
    final long longSize = (long) len * (long) count;
    final int size = (int) longSize;
    if (size != longSize) {
        throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);
    }

    final char[] array = new char[size];
    string.getChars(0, len, array, 0);
    int n;
    for (n = len; n < size - n; n <<= 1) {
        System.arraycopy(array, 0, array, n, n);
    }
    System.arraycopy(array, 0, array, n, size - n);
    return new String(array);
}

repeat方法用来对一个字符串进行count次的重复,返回生成的字符串。
这里最难理解的地方在copy这个部分。

  • 首先需要理解System.arraycopy(char[] a, int s1, char[] b, int s2, int len)方法的参数和意义:
    这个方法用于数组间的拷贝,a是源数组,b是目的数组,s1是源数组的其实位置,s2是目的数组的起始位置,len是copy的长度。

  • string.getChars(0, len, array, 0)
    先把要repeat的字符串放在数组的开头,copy一份。

  • 成倍复制,指数递增:
    n<<=1 表示将n左移一位,再将值赋给n,相当于使n乘2。这里的for每一次都会吧array中已经有字符的一部分再拷贝给自己,速度是指数增长的,效率高。
    循环结束条件是:n<size-n . n和size之间是有整数倍关系的,size-n仍是n的整数倍,最后一次copy不在for中,只是在array中从位置0开始,到size-n结束截取一段,在拷贝给自己,复制结束。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 数组是一种可变的、可索引的数据集合。在Scala中用Array[T]的形式来表示Java中的数组形式 T[]。 v...
    时待吾阅读 4,596评论 0 0
  • ———————————————回答好下面的足够了---------------------------------...
    恒爱DE问候阅读 5,706评论 0 4
  • 一、(一共三十题) 1.main() { int a[5]={1,2,3,4,5}; int *ptr=(int ...
    iOS_Alex阅读 4,589评论 0 0
  • 曲链接——《烟火》 小桥初见风无言 粉面含春花惊艳 羞向栏杆觅鲜妍 已落 心间 梅雨点点燕缱绻 伊人秋千思...
    楠桢阅读 4,227评论 0 0

友情链接更多精彩内容