Guava | Strings

Guava | Strings_第1张图片

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

你可能感兴趣的:(Guava | Strings)