String的replzce源码解析

来源:互联网 发布:贪吃蛇大作战 数据 编辑:程序博客网 时间:2024/06/01 09:08
 public String replace(char oldChar, char newChar) {        if (oldChar != newChar) {//判断相等不 相等直接返回当前对象            int len = value.length;            int i = -1;            char[] val = value; /* avoid getfield opcode */            while (++i < len) {//这个循环减少了循环次数,什么时候相等了跳出循环证明前边都不想等不需要动了                if (val[i] == oldChar) {                    break;                }            }            if (i < len) {//赋值相等之前所有的                char buf[] = new char[len];                for (int j = 0; j < i; j++) {                    buf[j] = val[j];                }                while (i < len) {//想等了就替换掉                    char c = val[i];                    buf[i] = (c == oldChar) ? newChar : c;                    i++;                }                return new String(buf, true);            }        }        return this;    }

原创粉丝点击