String中的replace方法

  String中的replace(char oldchar,char newchar)方法意思將這個字符串中的全部的oldchar所有換成newchar,並返回一個新的字符串(這一點很重要)this

  讓我來看看這個方法的源碼:spa

  

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;
    }

  這一點總是忘記,總是覺得這個方法會自動的幫我去修改我原來的字符串,搞得好屢次都找不到錯誤,因此當咱們要改變原來字符串的時候只須要用原來的字符串去接replace()方法以後的返回,即: str=str.replace(oldchar,newchar) ,這樣的話就能達到對原字符串進行修改的目的了。code

相關文章
相關標籤/搜索