建议:repeat [自己先实现一个,然后对比一下guava的实现]
注意google工程师使如何使用StringBuilder这个类的
public static String repeat(String string, int count) { Preconditions.checkNotNull(string); if (count <= 1) { Preconditions.checkArgument(count >= 0, "invalid count: %s", count); return count == 0 ? "" : string; } else { int len = string.length(); long longSize = (long)len * (long)count; int size = (int)longSize; if ((long)size != longSize) { throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); } else { 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); } } }
如果让自己写的话,也就是for循环用StringBuilder累加一下就完事了,看guava的代码,确实鲁棒性要高的太多,自己想到的问题和没想到的问题别人都想到了。
把count <=1 的情况分裂出来,不仅避免了参数错误问题,也避免浪费一点点性能。
实现的时候用了一个数组取复制成数组,比StringBuilder要快
其他几个方法
public static String padEnd(String string, int minLength, char padChar)
返回一个长度至少为minLength的字符串,该字符串由附加了尽可能多的padChar副本的字符串组成,以达到该长度。
public static String padStart(String string, int minLength, char padChar)
返回一个长度至少为minLength的字符串,该字符串由字符串组成,字符串前面加上达到该长度所需的尽可能多的padChar副本。
public static String nullToEmpty(@Nullable String string) { return string == null ? "" : string; }
public static String emptyToNull(@Nullable String string) { return isNullOrEmpty(string) ? null : string; } public static boolean isNullOrEmpty(@Nullable String string) { return Platform.stringIsNullOrEmpty(string); }