偶尔看了下String类的源码,发现replace方法replace(char oldChar, char newChar)他是这样写的。
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;
}感觉写的比较麻烦,个人感觉好多代码可以不写.为什么替换不在第一个while找到oldchar的时候就替换了。而要放到下面来做?
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;
}感觉写的比较麻烦,个人感觉好多代码可以不写.为什么替换不在第一个while找到oldchar的时候就替换了。而要放到下面来做?
而上面我说过的方法不管有没有需要替换的字符,都会复制一次。在没有字符需要替换的情况下,效率比较低,而且返回的不是本对象的引用