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();
}