日期:2014-05-16  浏览次数:20393 次

请教大牛们一个问题
字符串的 public String replace(char oldChar,
  char newChar)

该方法具体是怎么实现的? 哪里可以查到? API里面只讲了用法,没给出实现啊

------解决方案--------------------
http://www.cnblogs.com/mahaisong/archive/2011/02/28/1967208.html
------解决方案--------------------
Java? 这里是Javascript板块。

想看实现的话,去JDK里面找吧,里面有源码。
------解决方案--------------------
JDK 源代码:
/**
* Returns a new string resulting from replacing all occurrences of 
* <code>oldChar</code> in this string with <code>newChar</code>. 
* <p>
* If the character <code>oldChar</code> does not occur in the 
* character sequence represented by this <code>String</code> object, 
* then a reference to this <code>String</code> object is returned. 
* Otherwise, a new <code>String</code> object is created that 
* represents a character sequence identical to the character sequence 
* represented by this <code>String</code> object, except that every 
* occurrence of <code>oldChar</code> is replaced by an occurrence
* of <code>newChar</code>. 
* <p>
* Examples:
* <blockquote><pre>
* "mesquite in your cellar".replace('e', 'o')
* returns "mosquito in your collar"
* "the war of baronets".replace('r', 'y')
* returns "the way of bayonets"
* "sparring with a purple porpoise".replace('p', 't')
* returns "starring with a turtle tortoise"
* "JonL".replace('q', 'x') returns "JonL" (no change)
* </pre></blockquote>
*
* @param oldChar the old character.
* @param newChar the new character.
* @return a string derived from this string by replacing every
* occurrence of <code>oldChar</code> with <code>newChar</code>.
*/
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;
}