Strings
Stirngs是Guava对字符串操作提供的一些支持。
// 将null转为空字符串,不为null返回源字符串
public static String nullToEmpty(@Nullable String string) {
return (string == null) ? "" : string;
}
// 将空字符串转为null,不为空返回源字符串
@Nullable
public static String emptyToNull(@Nullable String string) {
return isNullOrEmpty(string) ? null : string;
}
// 判断字符串是null或者空
public static boolean isNullOrEmpty(@Nullable String string) {
return Platform.stringIsNullOrEmpty(string);
}
// 对于给定的string,如果长度小于minLength,在string首部填充padChar
public static String padStart(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
// 首部填充
sb.append(string);
return sb.toString();
}
// 对于给定的string,如果长度小于minLength,在string尾部填充padChar
public static String padEnd(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
sb.append(string);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
return sb.toString();
}
// 将string重复count倍返回
public static String repeat(String string, int count) {
checkNotNull(string); // eager for GWT.
if (count <= 1) {
// count >= 0 不成立,抛出IllegalArgumentException
checkArgument(count >= 0, "invalid count: %s", count);
// count=0,返回空,count=1,返回源字符串
return (count == 0) ? "" : string;
}
// IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
final int len = string.length();
// 将repeat之后的长度len*count转为long类型
final long longSize = (long) len * (long) count;
// 判断repeat之后的长度为int类型时会不会发生截断
final int size = (int) longSize;
if (size != longSize) {
throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);
}
// 复制,使用char数组进行字符串装载
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);
}
// 返回公共最长前缀,无公共前缀返回空字符串
public static String commonPrefix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxPrefixLength = Math.min(a.length(), b.length());
int p = 0;
while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
p++;
}
if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
p--;
}
return a.subSequence(0, p).toString();
}
// 返回公共最长后缀,无公共后缀返回空字符串
public static String commonSuffix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxSuffixLength = Math.min(a.length(), b.length());
int s = 0;
while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
s++;
}
if (validSurrogatePairAt(a, a.length() - s - 1)
|| validSurrogatePairAt(b, b.length() - s - 1)) {
s--;
}
return a.subSequence(a.length() - s, a.length()).toString();
}