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

Go To StackoverFlow.com

0

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("‘", "'");
}
2012-04-03 19:46
by Webnet


1

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

2012-04-03 19:52
by Mizuho
Doesn't this call public String replace(CharSequence target, CharSequence replacement)? As far as I understand from javadocs, your code would be equal to body.replace("“—‘", "\"-'"), which is not what is wanted - hyde 2013-01-11 12:49


1

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.

2012-04-03 19:51
by ControlAltDel
Ads