0

How can I edit a string with double quotes and backslashes like this one

"i love \"programming\""

and print like this

i love "programming"

I found this online but no luck:

for (int i = 0; i < lineLength; i++)
{
    if (line[i] == '\\')
    {
        line[j++] = line[i++];
        line[j++] = line[i];
        if (line[i] == '\0')
            break;
    }
    else if (line[i] != '"')
        line[j++] = line[i];
}
line[j] = '\0';
Stephen
  • 1,607
  • 2
  • 18
  • 40
  • I just searched stack overflow for "Remove quotes in C" - this was the #1 response: http://stackoverflow.com/questions/7143878/how-to-remove-quotes-from-a-string-in-c – Doug Kress Aug 23 '11 at 01:06
  • @michael15 Can you change the code in your question into a full C function, and include some sample input and expected output? We need to know what problem you've run into. – Dan Cecile Aug 23 '11 at 01:27
  • Why do you need to do anything to it? It will print the way you want the way it is. – user207421 Aug 23 '11 at 02:14
  • @michael15 There will be a link at the end of your question that says "edit". You can use it to change your question. (See [this FAQ](http://meta.stackexchange.com/questions/21788/how-does-editing-work/21789#21789) for details.) The "Answer" section is where solutions get posted. – Dan Cecile Aug 23 '11 at 02:26

2 Answers2

1

When you encounter a backslash, you're currently copying the backslash AND the next character. What you actually need to do is just increment past the backslash and then copy the next character as you do when its not a backslash or a quote. Instead of line[j++] = line[i++]; (for the first line in your if body) you just need i++;.

There are some other things you could fix up as well, but that should get it working.

Dmitri
  • 9,175
  • 2
  • 27
  • 34
0

IMHO the read/write pointer approach is one of the simplest when dealing with these problems of removing characters, it makes the algorithm easy to follow.

void RemoveQuotes(char * Str)
{
    const char * readPtr=Str;
    char * writePtr=Str;
    for( ;*readPtr; readPtr++, writePtr++)
    {
        /* Checks the current character */
        switch(*readPtr)
        {
            case '\"':
                /* if there's another character after this, skip the " */
                if(readPtr[1])
                    readPtr++;
                /* otherwise jump to the check and thus exit from the loop */
                else
                    continue;
                break;
            case '\\':
                /* if a " follows, move readPtr ahead, so to skip the \ and copy
                   the "; otherwise nothing special happens */
                if(readPtr[1]=='\"')
                    readPtr++;
                break;
        }
        /* copy the characters */
        *writePtr=*readPtr;
    }
    /* remember to NUL-terminate the string */
    *writePtr=0;
}
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299