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];
}
//為什么不一開(kāi)始用這個(gè)循環(huán)?
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}
因?yàn)樾枰袻inux路徑分隔符轉(zhuǎn)化為Windows下的,就先自己寫(xiě)了個(gè),還是蠻有差距的。
這個(gè)的思想是先把第一次出現(xiàn)oldChar之前的字符復(fù)制過(guò)去,再遍歷接下來(lái)的,這樣做比只用第二個(gè)while的好處我只想到一點(diǎn),就是在沒(méi)有匹配到oldChar時(shí),省去了復(fù)制這一步。