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