Reputation: 9435
How can I parse a string and replace all occurences of a \.
with something? Yet at the same time replace all \\
with \
(literal).. Examples:
hello \. world
=> hello "." world
hello \\. world
=> hello \. world
hello \\\. world
=> hello \"." world
The first reaction was to use std::replace_if, as in the following:
bool escape(false);
std::replace_if(str.begin(), str.end(), [&] (char c) {
if (c == '\\') {
escape = !escape;
} else if (escape && c == '.') {
return true;
}
return false;
},"\".\"");
However that simply changes \.
by \"."
sequences. Also it won't be working for \\
parts in the staring.
Is there an elegant approach to this? Before I start doing a hack job with a for loop & rebuilding the string?
Upvotes: 1
Views: 1797
Reputation: 88
Elegant approach: a finite state machine with three states:
To implement you could use the iterators in the default string library and the replace
method.
http://www.cplusplus.com/reference/string/string/replace/
Upvotes: 2