0

I apologize if this already has been answered but I didn't manage to find a solution on exactly this. I want to find all occurrences of a specific substring in a string and then replace those substrings with something else, for example:

int main(){
    // Variabeldeklaration
    string str = "elephant elephant duck duck elephant";

    if (/* string contains "elephant" */){
        // replace_all "elephant" , "gorilla";
    }

    // Now str = "gorilla gorilla duck duck gorilla";

    system("PAUSE");
    return 0;
}

I know it's possible to replace all char found in a string but I want to be able to replace more than one char. How do I do this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
enheldel
  • 3
  • 5
  • 4
    Possible duplicate of [Replace part of a string with another string](http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string). Or [Replace substring with another substring C++](http://stackoverflow.com/questions/4643512/replace-substring-with-another-substring-c). Or [How do I replace all instances of a string with another string?](http://stackoverflow.com/questions/5343190/how-do-i-replace-all-instances-of-a-string-with-another-string). – Wiktor Stribiżew Dec 28 '16 at 11:29
  • I found that answer earlier, however this does only replace the first substring it finds and not all of them. – enheldel Dec 28 '16 at 14:44
  • *That* - which one? The third link is actually what you need. Besides, replacing `if` with `while` is not a rocket science. – Wiktor Stribiżew Dec 28 '16 at 14:46
  • Sorry I clicked the link on top of the page, thanks – enheldel Dec 28 '16 at 15:59
  • I cannot reclose as I already cast a close vote. I do not think reclosing is that necessary though. – Wiktor Stribiżew Dec 28 '16 at 16:34
  • Was there another of the questions that Wiktor linked that you'd rather have this one closed as a duplicate of? I can change the duplicate if that would make the answer easier to find. – Cody Gray - on strike Dec 28 '16 at 18:21

0 Answers0