日期:2014-05-20  浏览次数:20670 次

JDK1.5中String.replace()的实现有点奇怪
最近在看JDK1.5的源码,看到String.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;
}


里面是先找到oldChar,break掉,再把前面的字符循环放到新的数组中,然后从此开始判断,如果相等就替换。
其他的不说,就最前面循环找到oldChar再循环放入数组的操作中,就多做了一次循环。这个是不是没有必要啊?还是有什么内幕?请大虾们指教。

---------------------------------------
下半部分的while和if两块代码是不是可以整合起来,在循环中直接赋值和替换,如下:

                        char buf[] = new char[len];
for (int i = 0, j = 0; i < len; i++) {
if (val[off + i] == oldChar) {
buf[j++] = newChar;
}
else {
buf[j++] = val[off + i];
}
}


或者干脆先copy到一个新的数组中,再寻找oldChar然后替换,如下:

                        char buf[] = new char[len];
System.arraycopy(val, 0, buf, 0, len);
for (int i = 0, j = 0; i < len; i++) {
if (val[off + i] == oldChar) {
buf[j++] = newChar;
}
}


请大虾们指教!!
------最佳解决方案--------------------
这样做的好处是当找不到要替换的字符时,无需创建一个新的 String
------其他解决方案--------------------
你先调试下 看看你自己的办法会不会比  jdk原先的替换方法快。 建议循环1亿次以上 。 如果有必要 ,最好加上多线程
------其他解决方案--------------------
木有人路过? 自己顶一下
------其他解决方案--------------------
查一下API文档:
replace()
public String replace(char oldChar,
                      char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 
如果 oldChar 在此 String 对象表示的字符序列中没有出现,则返回对此 String 对象的引用。否则,创建一个新的 String 对象,它所表示的字符序列除了所有的 oldChar 都被替换为 newChar 之外,与此 String 对象表示的字符序列相同。 

示例: 



"mesquite in your cellar".replace('e', 'o')
         returns "mosquito in your collar"