Spring-API简析_org.springframework.util.StringUtils类(基于 Latest JDK)(浅析源码)

【版权声明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)
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]

本文持续更新中。。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进步·于辰

谢谢打赏!!很高兴可以帮到你!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值