How to find and replace all occurrences of a substring in a string?

前端 未结 7 1512
无人共我
无人共我 2020-12-31 06:49

I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences

7条回答
  •  清歌不尽
    2020-12-31 07:19

    The find function takes an optional second argument: the position from which to begin searching. By default this is zero.

    A good position to begin searching for the next match is the position where the previous replacement was inserted, plus that replacement's length. For instance if we insert a string of length 3 at position 7, then the next find should begin at position 10.

    If the search string happens to be a substring of the replacement, this approach will avoid an infinite loop. Imagine if you try to replace all occurrences of log with analog, but don't skip over the replacement.

提交回复
热议问题