If you need to process more than one escape, I suggest you take the source string, and copy it to destination string one character at a time. Both strings can actually be the same, if you want to work in place. You keep separate index for each. While reading the source, if you hit a backslash, instead of just copying it, you advance the source-index only, looking at the next character to see what kind of escape it is, and then write the escaped special character instead of the two characters. This way you only have to go over the string once.
It's been too long since I used STL strings for anything, so I'll give an example in C:
Code: Select all
// replaces \n with newline, \e with escape, \b with backspace and \\ with \
// returns -1 and prints error if other escapes are encountered
int replace_escapes(char * dest, const char * src) {
int si = 0, di = 0;
while(src[si]) {
if(src[si] == '\\') {
switch(src[++si]) {
case 'e': dest[di] = '\033'; break;
case 'n': dest[di] = '\n'; break;
case 'b': dest[di] = '\b'; break;
case '\\': dest[di] = '\\'; break;
default: fprintf(stderr, "invalid escape \\%c\n", src[si]); return -1;
} else {
dest[di] = src[si];
}
++si; ++di;
}
}
The real problem with goto is not with the control transfer, but with environments. Properly tail-recursive closures get both right.