title: How to find and replace all occurrences of a substring in a string?
body: <p>I need to search a string and edit the formatting of it.</p>
  
  <p>So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences of this string.</p>
  
  <p>This is what I have working, sort of:</p>
  
  <pre><code>if(chartDataString.find("*A") == string::npos){ return;}
  else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}
  </code></pre>
  
  <p>If it doesn't find the string, nothing prints at all, so that's not good.</p>
  
  <p>I know I need to loop through the entire string chartDataString and replace all occurrences.  I know there are a lot of similar posts to this but I don't understand  (like this <a href="https://stackoverflow.com/questions/4643512/replace-substring-with-another-substring-c">Replace substring with another substring C++</a>)</p>
  
  <p>I've also tried to do something like this to loop over the string:</p>
  
  <pre><code>string toSearch = chartDataString;
  string toFind = "*A:";
  for (int i = 0; i&lt;toSearch.length() - toFind.length(); i++){
     if(toSearch.substr(i, toFind.length()) == toFind){
         chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");   
     }
  }
  </code></pre>
  
  <p>EDIT
  taking into consideration suggestions, this in theory should work, but I don't know why it doesn't</p>
  
  <pre><code>size_t startPos=0;
  string myString = "*A";
  while(string::npos != (startPos = chartDataString.find(myString, startPos))){
      chartDataString.replace(chartDataString.find(myString, startPos), 3, "*A\n");
      startPos = startPos + myString.length();
  }   
  </code></pre>