Sarah Sarah - 1 year ago 215
C++ Question

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

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");

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 Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download