Best way to replace multiple characters in a string?

前端 未结 14 1998
遇见更好的自我
遇见更好的自我 2020-11-22 11:15

I need to replace some characters as follows: &\\&, #\\#, ...

I coded as follows, but I guess there

14条回答
  •  执笔经年
    2020-11-22 11:31

    Late to the party, but I lost a lot of time with this issue until I found my answer.

    Short and sweet, translate is superior to replace. If you're more interested in funcionality over time optimization, do not use replace.

    Also use translate if you don't know if the set of characters to be replaced overlaps the set of characters used to replace.

    Case in point:

    Using replace you would naively expect the snippet "1234".replace("1", "2").replace("2", "3").replace("3", "4") to return "2344", but it will return in fact "4444".

    Translation seems to perform what OP originally desired.

提交回复
热议问题