On Mon, 2005-11-07 at 12:39 -0700, Tom Tromey wrote:
"Tony" == Anthony Balkissoon <address@hidden> writes:
Tony> + public String replace (CharSequence target, CharSequence replacement)
Tony> + {
Tony> + String result = this;
Tony> + int pos = result.indexOf(target.toString());
Tony> + while (pos != -1)
Tony> + {
Tony> + result = result.substring(0, pos) + replacement.toString()
Tony> + + result.substring(pos + target.length(),
result.length());
Tony> + pos = result.indexOf(target.toString());
Tony> + }
Tony> + return result;
Tony> + }
Tony> }
This is inefficient. For one thing, target is converted to a String
twice. For another, it creates a lot of garbage if there is more than
one match.
It is also incorrect, consider what happens if the replacement string
contains the target string.
Thanks Tom. I fixed this now, it uses a StringBuffer for better
performance and also only checks for occurrences of the target string