【版权声明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)
https://blog.csdn.net/m0_69908381/article/details/132594530
出自【进步*于辰的博客】
1、概述
在我们日常开发过程中,对字符串的操作是非常频繁的,但JDK提供的对于字符串操作的方法过于简单,无法满足我们开发中的需求。
此类统一封装了字符串相关操作的方法。
2、方法摘要
2.1 判空
示例:
public static boolean isEmpty(@Nullable Object str) {
return (str == null || "".equals(str));
}
public static boolean hasLength(@Nullable String str) {
return (str != null && !str.isEmpty());
}
2.2 去掉空格
对于后端的很多接口,经常需要去掉前后空格,我们可以使用String类的trim()
,但是如果要同时去掉中间的空格呢?
示例:
public static StringtrimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
int len = str.length();
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
2.3 判断开头或结尾字符串
要判断一个字符串,是不是以某个固定字符串开头或者结尾,是非常常见的需求。
示例:
public static boolean startsWithIgnoreCase(@Nullable String str, @Nullable String prefix) {
return (str != null && prefix != null && str.length() >= prefix.length() &&
str.regionMatches(true, 0, prefix, 0, prefix.length()));
}
public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix) {
return (str != null && suffix != null && str.length() >= suffix.length() &&
str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length()));
}
2.4 集合拼接字符串
有时候我们需要将某个字符串集合的所有元素,拼接成一个字符串,用逗号隔开。
示例:
public static String collectionToCommaDelimitedString(Collection<?> coll) {
return collectionToDelimitedString(coll, ",");
}
public static String collectionToDelimitedString(@Nullable Collection<?> coll, String delim) {
return collectionToDelimitedString(coll, delim, "", "");
}
public static String collectionToDelimitedString(
@Nullable Collection<?> coll, String delim, String prefix, String suffix) {
if (CollectionUtils.isEmpty(coll)) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
if (it.hasNext()) {
sb.append(delim);
}
}
return sb.toString();
}
List<Integer> list = Arrays.asList(2, 0, 2, 4);
StringUtils.collectionToDelimitedString(list, "-", "[", "]");// [2]-[0]-[2]-[4]
本文持续更新中。。。