Because String
is immutable you should use StringBuilder
for better performance.
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
yourStringBuiler.replace(
yourStringBuiler.indexOf(oldString),
yourStringBuiler.indexOf(oldString) + oldString.length(),
newString);`
If you want to replace a whole String
like the String.replaceAll()
does you could create an own function like this:
public static void replaceAll(StringBuilder builder, String from, String to)
{
int index = builder.indexOf(from);
while (index != -1)
{
builder.replace(index, index + from.length(), to);
index += to.length(); // Move to the end of the replacement
index = builder.indexOf(from, index);
}
}
Source:
Replace all occurrences of a String using StringBuilder?
However if you doesn't need it frequently and performance is not that important a simple String.replaceAll()
will do the trick, too.