Ben
Ben

Reputation: 62366

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("‘", "'");
}

Upvotes: 0

Views: 82

Answers (2)

Mizuho
Mizuho

Reputation: 90

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

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

You are right. To solve this, you should create a StringBuilder and go through your string 1 character at a time, adding the character to the stringBuilder if it is correct or replacing if it is wrong.

Upvotes: 1

Related Questions