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]
");}
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]
");
}
}
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
");
startPos = startPos + myString.length();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…