Here is a simple algorithm that does the job:
#include <iostream>
#include <string>
using namespace std;
string replace(char c, string replacement, string s)
{
string chars = string("\\") + c;
size_t pos = s.find_first_of(chars);
while (pos != string::npos)
{
char& ch = s[pos];
if (ch == '\\')
{
pos = s.find_first_of(chars, pos + 2);
}
else if (ch == c)
{
s.replace(pos, 1, replacement);
pos = s.find_first_of(chars, pos + replacement.length());
}
}
return s;
}
int main()
{
cout << replace('\'', "''", "hello \\'world'");
}
UPDATE:
Following @BenVoigt's suggestion, I reformulated the algorithm to avoid in-place operations. This should lead to a further increase in productivity:
string replace(char c, string replacement, string const& s)
{
string result;
size_t searchStartPos = 0;
string chars = string("\\") + c;
size_t pos = s.find_first_of(chars);
while (pos != string::npos)
{
result += s.substr(searchStartPos, pos - searchStartPos);
if (s[pos] == '\\')
{
result += string("\\") + c;
searchStartPos = pos + 2;
}
else if (s[pos] == c)
{
result += replacement;
searchStartPos = pos + 1;
}
pos = s.find_first_of(chars, searchStartPos);
}
return result;
}
source
share