Search code examples
java-6

Run multiple string replaces with fewer calls to .replace()


I'd like to condence the following code into fewer calls to .replace(). It doesn't look like .replace() will do this. Am I right or am I just reading the documentation wrong?

public void setBody(String body) {
    this.body = body.replace("“", "\"").replace("”", "\"").replace("—", "-").replace("’", "'").replace("‘", "'");
}

Solution

  • You should be able to use body.replace(['"', '—', '‘'], ['\"', '-', "'"]).