IT评测·应用市场-qidao123.com
标题:
【Guava工具类】Strings&Ints
[打印本页]
作者:
徐锦洪
时间:
2025-3-24 08:39
标题:
【Guava工具类】Strings&Ints
String相关工具
Strings
Guava 提供了一系列用于字符串处理的工具:
对字符串为null或空的处理
nullToEmpty(@Nullable String string):假如非空,则返回给定的字符串;否则返回空字符串
public static String nullToEmpty(@Nullable String string) {
//如果string为null则返回空字符串,否则返回给定的string
return string == null ? "" : string;
}
复制代码
.isNullOrEmpty(@Nullable String string):假如字符串为空或长度为0返回true,否则返回false
public static boolean isNullOrEmpty(@Nullable String string) {
return string == null || string.length() == 0;
}
复制代码
emptyToNull(@Nullable String string):假如非空,则返回给定的字符串;否则返回null
public static String emptyToNull(@Nullable String string) {
//调用isNullOrEmpty方法,如果返回true则return null,否则返回原字符串
return isNullOrEmpty(string)?null:string;
}
复制代码
天生指定字符串的字符串副本
<ol>padStart(String string, int minLength, char padChar):根据传入的minLength进行补充,假如minLength小于原来字符串的长度,则直接返回原来字符串,否则在字符串开头添加string.length() - minLength个padChar字符
public static String padStart(String string, int minLength, char padChar) {
//使用Preconditions工具类进行字符串验空处理
Preconditions.checkNotNull(string);
//如果原字符串长度大于传入的新长度则直接返回原字符串
if(string.length() >= minLength) {
return string;
} else { //否则
StringBuilder sb = new StringBuilder(minLength);
//先在字符串前面添加string.length()-minLength个padChar字符
for(int i = string.length(); i < minLength; ++i) {
sb.append(padChar);
}
//最后将原始字符串添加到尾部
sb.append(string);
return sb.toString();
}
}
复制代码
padEnd(String string, int minLength, char padChar):根据传入的minLength进行补充,假如minLength小于原来字符串的长度,则直接返回原来字符串,否则在字符串结尾添加 string.length() - minLength 个padChar字符
public static String padEnd(String string, int minLength, char padChar) {
Preconditions.checkNotNull(string);
//如果原字符串长度大于传入的新长度则直接返回原字符串
if(string.length() >= minLength) {
return string;
} else {
StringBuilder sb = new StringBuilder(minLength);
//先将原始字符串添加到预生成的字符串当中
sb.append(string);
//在使用padChar进行填补
for(int i = string.length(); i < minLength; ++i) {
sb.append(padChar);
}
return sb.toString();
}
}
复制代码
repeat(String string, int count):返回count个 string字符串拼接成的字符串
[code]public static String repeat(String string, int count) { Preconditions.checkNotNull(string); //假如小于1,则抛出异常 if(count = 0, "invalid count: %s", new Object[]{Integer.valueOf(count)}); return count == 0 ? "":string; } else { int len = string.length(); long longSize = (long)len * (long)count; int size = (int)longSize; //假如新创建的字符串长度超出int最大值,则抛出须要的数组过长的异常 if((long)size != longSize) { throw new ArrayIndexOutOfBoundsException((new StringBuilder(51)).append("Required array size too large: ").append(longSize).toString()); } else { //实际上新建一个相称长度的字符数组,再将数据复制进去 char[] array = new char[size]; //将string从0开始len竣事之间的字符串复制到array数组中,且array数组从0开始存储 string.getChars(0, len, array, 0); int n; //复制数组,复制的步长为(1,2,4...n^2),所以这快提供了一个外层循环为ln2的算法 for(n = len; n < size - n; n
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4