这篇文章就一个内容
解析String中的repalce的源码
源码:
public String replace(CharSequence target, CharSequence replacement) {
String tgtStr = target.toString();
String replStr = replacement.toString();
int j = indexOf(tgtStr);
if (j < 0) {
return this;
}
int tgtLen = tgtStr.length();
int tgtLen1 = Math.max(tgtLen, 1);
int thisLen = length();
int newLenHint = thisLen - tgtLen + replStr.length();
if (newLenHint < 0) {
throw new OutOfMemoryError();
}
StringBuilder sb = new StringBuilder(newLenHint);
int i = 0;
do {
sb.append(this, i, j).append(replStr);
i = j + tgtLen;
} while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
return sb.append(this, i, thisLen).toString();
}
分析:
//前置知识
//indexOf(tgtStr) 查找目标字符串在原字符串第一次出现位置的索引
//indexOf(Str,index) 查找目标字符串在原字符串中指定的位置之后出现的第一次出现的位置的索引
public String replace(CharSequence target, CharSequence replacement) {
//字符序列转换成字符串
String tgtStr = target.toString(); //替换的字符串
String replStr = replacement.toString(); //目标字符串
/*
原字符串 String a = "aa"
target表示被替换的字符串
比如 target = "aa" replacement = "bb"
则就变成了aa
target = "aaa" replacement = "bb"
就变成了aab
target = "a" replacement = "bb"
bbbb
*/
//如果目标子串不在原字符串中,返回原字符串
int j = indexOf(tgtStr);
if (j < 0) {
return this;
}
int tgtLen = tgtStr.length();//目标子串的长度
int tgtLen1 = Math.max(tgtLen, 1);//和1比较大小
int thisLen = length();//原字符串长度
int newLenHint = thisLen - tgtLen + replStr.length();//计算新字符串的长度
//如果是负数,则分配内存失败
if (newLenHint < 0) {
throw new OutOfMemoryError();
}
//构建长度为newLenHint的拼接对象
StringBuilder sb = new StringBuilder(newLenHint);
int i = 0;
/*
public StringBuilder append(char[] str,
int offset,
int len)
char[] str == this 拼接的字符
nt offset == i 插入点
int len == j 追加的字符的数量
*/
do {
sb.append(this, i, j).append(replStr);
i = j + tgtLen;//下一个拼接的点
} while (j < thisLen && (j = indexOf(tgtStr, j + tgtLen1)) > 0);
// j < thisLen 追加的字符的数量 < 原字符串的长度
// j = indexOf(tgtStr, j + tgtLen1)) > 0
//indexOf(tgtStr, j + tgtLen1) 对象在指定字符串,指定的索引中,第一次出现的索引 =》寻找目标子串下一个插入的位置
return sb.append(this, i, thisLen).toString();
}