1

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?

2
  • 1
    You should be replacing strings, e.g. "\\\\" -> "\\", "\\x" -> "x"; not chars. Commented Jan 26, 2012 at 17:59
  • I think "a hack job with a for loop & rebuilding the string" would be the least ugly solution. Commented Jan 26, 2012 at 18:17

1 Answer 1

2

Elegant approach: a finite state machine with three states:

  • looking for '\' (iterating through string)
  • found '\' and next character is '.'
  • found '\' and next character is '\'

To implement you could use the iterators in the default string library and the replace method.

http://www.cplusplus.com/reference/string/string/replace/

Sign up to request clarification or add additional context in comments.

3 Comments

uhm HOW would I use the replace method then? Especially since if you remove elements from a container the iterators get invalidated..
You could start a new iterator from where the pattern was found on the last string plus the size of the string you inserted. Actually, I think it would more obvious just use the string's operator[], with an integer index.
I think it'd be simpler not to use string.replace but to build a new string from the original, character by character. Regardless, an FSM is definitely the way to go here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.