jeudi 30 avril 2015

Move a chunk of text within a std::string to the left by X amount of chars

What is an efficient way to shift the text within a std::string, starting at some offset, to the left by X amount of characters?

Example:

[Some sTring here]

Shifted to the left by 1, starting at T, would yield:

[Some Tring here]

Background Info

I'm writing a compiler in C++ for a small text templating language, in which text of the form:

{some expression here}

represent expressions to be replaced with some value. Those expressions can appear interspersed with text; something like the following:

There are {$count} types of things.

The above would be replaced with something like the following, after the text is evaluated by the compiler.

There are 42 types of things.

I'm doing all the processing of the text within a std::string object. Basically, calling std::replace() alot.

Now, I want support the ability to 'escape' expressions, so that text that would normally represent expressions can be written verbatim. So this:

There are \{$count} types of things.

would be outputted like this:

There are {$count} types of things.

Basically, all that needs to happen is for the text after There are to be moved by 1 byte to the left. I was trying to think of an efficient way to do this. I wish I could memmove std::string's data buffer from '{...' by 1 byte to the left, but I'm not sure if that's possible. So, I'm hoping there is a better way than to do something like this:

auto s = buffer.size()
auto temp = buffer.substr(bracePos, s - bracePos)
buffer.assign(temp, bracePos - 1)
buffer.resize(s - 1)

Is there a better way to do this? I hate the idea of copying a big chunk of a string just to move the contents to the left by 1 character.

Aucun commentaire:

Enregistrer un commentaire