StringUtils.replace用法,加源码解释!小白通俗易懂!

本文主要介绍了StringUtils工具类的替换方法。包括replace方法将text中所有searchString替换成replacement,还有replaceOnce只替换一次、replaceChars按字符替换等。此外,还讲解了按数组替换的方法,如replaceEach和replaceEachRepeatedly。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

StringUtils.replace用法
首先我们先看源码:

public static String replace(String text, String searchString, String replacement, int max) {
        if (!isEmpty(text) && !isEmpty(searchString) && replacement != null && max != 0) {
            int start = 0;
            int end = text.indexOf(searchString, start);
            if (end == -1) {
                return text;
            } else {
                int replLength = searchString.length();
				//获取被替换文本长度
                int increase = replacement.length() - replLength;
				//获取替换文本长度与被替换文本长度的差。
                increase = increase < 0 ? 0 : increase;
                increase *= max < 0 ? 16 : (max > 64 ? 64 : max);

                StringBuffer buf;
				//定义StringBuffer,且定义长度。
                for(buf = new StringBuffer(text.length() + increase); end != -1; end = text.indexOf(searchString, start)) {
					//end是被替换文本的开始位置
                    buf.append(text.substring(start, end)).append(replacement);
					//将被替换文本之前的文本append到buf中,然后append替换文本
                    start = end + replLength;
					//start位置更新,下次循环从新的位置开始,迭代该方法
                    --max;
                    if (max == 0) {
                        break;
                    }
                }
                buf.append(text.substring(start));
                return buf.toString();
            }
        } else {
            return text;
        }
    }

作用:将text中所有的searchString替换成replacement。max为最大替换次数
源码思路:
在这里插入图片描述

其他方法:
StringUtils.replaceOnce(“我是ly,来自ly”, “ly”, “bj”);//只替换一次–>结果是:我是bj,来自ly

StringUtils.replace(“我是ly,来自ly”, “ly”, “bj”);//全部替换 —> 结果是:我是bj,来自bj

StringUtils.replaceChars(“sshhhs”, “ss”, “p”);//替换所有字符,区别于replace —> 按照字符替换

2.按照数组进行替换,位置要匹配,数组长度要相等;
暂时没发现下面replaceEach和replaceEachRepeatedly二者的区别

StringUtils.replaceEach(“www.baidu.com”, new String[]{“baidu”,“com”}, new String[]{“taobao”,“cn”});//结果是:www.taobao.cn

StringUtils.replaceEach(“www.baidu,baidu.com”, new String[]{“baidu”,“com”}, new String[]{“taobao”,“cn”});//结果是:www.taobao,taobao.cn

StringUtils.replaceEachRepeatedly(“www.baidu.com”, new String[]{“baidu”,“com”}, new String[]{“taobao”,“cn”});//结果是:www.taobao.cn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值