做面试题有时候会遇到实现一些基本的java String方法而不用系统API,找出了replace的源代码,学习一下
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
;
}