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("‘", "'");
}
Jan Groth
  • 14,039
  • 5
  • 40
  • 55
Ben
  • 60,438
  • 111
  • 314
  • 488

2 Answers2

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.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

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

Mizuho
  • 90
  • 9
  • 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 Jan 11 '13 at 12:49