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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章