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

Sarah picture Sarah · Dec 5, 2013 · Viewed 24.8k times · Source

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 of this string.

This is what I have working, sort of:

if(chartDataString.find("*A") == string::npos){ return;}
else{chartDataString.replace(chartDataString.find("*A"), 3,"[A]\n");}

If it doesn't find the string, nothing prints at all, so that's not good.

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 Replace substring with another substring C++)

I've also tried to do something like this to loop over the string:

string toSearch = chartDataString;
string toFind = "*A:";
for (int i = 0; i<toSearch.length() - toFind.length(); i++){
   if(toSearch.substr(i, toFind.length()) == toFind){
       chartDataString.replace(chartDataString.find(toFind), 3, "[A]\n");   
   }
}

EDIT taking into consideration suggestions, this in theory should work, but I don't know why it doesn't

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();
}   

Answer

Vlad from Moscow picture Vlad from Moscow · Dec 6, 2013

try the following

const std::string s = "*A";
const std::string t = "*A\n";

std::string::size_type n = 0;
while ( ( n = chartDataString.find( s, n ) ) != std::string::npos )
{
    chartDataString.replace( n, s.size(), t );
    n += t.size();
}