How to replace all occurrences of a character in string?

后端 未结 15 1241
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

15条回答
  •  清酒与你
    2020-11-22 06:13

    If you're looking to replace more than a single character, and are dealing only with std::string, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.

    while(sHaystack.find(sNeedle) != std::string::npos) {
      sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
    }
    

提交回复
热议问题