replace string cpp code example
Example 1: c++ replace character in string
#include <algorithm>
#include <string>
void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y');
}
Example 2: c++ replace character in string
#include <string>
#include <regex>
using namespace std;
string test = "abc def abc def";
test = regex_replace(test, regex("abc"), "Ziv");
Example 3: c++ replace substrings
using namespace std;
string ReplaceAllSubstringOccurrences(string sAll, string sStringToRemove, string sStringToInsert)
{
int iLength = sStringToRemove.length();
size_t index = 0;
while (true)
{
index = sAll.find(sStringToRemove, index);
if (index == std::string::npos)
break;
sAll.replace(index, iLength, sStringToInsert);
index += iLength;
}
return sAll;
}
string sInitialString = "Replace this, and also this, don't forget this too";
string sFinalString = ReplaceAllSubstringOccurrences(sInitialString, "this", "{new word/phrase}");
cout << "[sInitialString->" << sInitialString << "]\n";
cout << "[sFinalString->" << sFinalString << "]\n";