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 = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
}
这是replace()源码,并没有把s指向修改后的String作者: 曾祥彬 时间: 2012-6-17 11:59
字符串类String对象的值是常量,一旦初始化是不能改变的
比如 String s = "hello";
那么s所指向的值是在内存中的一个地方,这个地方存放了字符串hello,这个字符串是常量,也就是说是不能被改变的。
并且,要清楚的是,上面的变量s只是一个引用,它的指向是可以改变的如下
String s = "hello";
s = "hello world";
这样 s 就指向了hello world,而hello 和 hello world这两个字符串是放在内存中的不同的地方的。
你用
s.replace('l','o');返回的s1是一个新的对象,这个新对象指向的内存单元的值是heooo,而 s 还是指向了原来的hello。
这样说不知道你明白了没?作者: 李海晓 时间: 2012-6-17 12:05
String s="hello";给s赋初值
String s1=s.replace('l','o'); 给s1赋初值,是将s中所有l换成o赋给s1
没有对s进行操作,所有没有改变.
String s=s.replace('l','o'); 才可以作者: 晏文根 时间: 2012-6-17 12:09 本帖最后由 晏文根 于 2012-6-17 12:12 编辑