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

Use std::regex_replace available with C++11. This does exactly what you want and more.

https://en.cppreference.com/w/cpp/regex/regex_replace

std::string const result = std::regex_replace( chartDataString, std::regex( "\\*A" ), "[A]\n" );

In case boost is available, you can use the following:

std::string origStr = "this string has *A and then another *A";
std::string subStringToRemove = "*A";
std::string subStringToReplace = "[A]";

boost::replace_all(origStr , subStringToRemove , subStringToReplace);

To perform the modification on the original string, OR

std::string result = boost::replace_all_copy(origStr , subStringToRemove , subStringToReplace);

To perform the modifications without modifying the original string.


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