Java API
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences ofoldCharin this string withnewChar.
source code
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */
while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
//为什么不一开始用这个循环?
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}
因为需要把Linux路径分隔符转化为Windows下的,就先自己写了个,还是蛮有差距的。
这个的思想是先把第一次出现oldChar之前的字符复制过去,再遍历接下来的,这样做比只用第二个while的好处我只想到一点,就是在没有匹配到oldChar时,省去了复制这一步。