String中的replace(char oldchar,char newchar)方法意思將這個字符串中的所有的oldchar全部換成newchar,並返回一個新的字符串(這一點很重要)
讓我來看看這個方法的源碼:
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) ,這樣的話就能達到對原字符串進行修改的目的了。
