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時,省去了復制這一步。