Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove quotes from a string in C

Tags:

c

quotes

I am trying to remove all quotes in a given line except a backslash followed by a quote

what I have done is this

for (int i = 0; i < lineLength; i ++) {

        if (line[i] == '"' ) { 
                if (line[i-1] == '\\') // if \" is used   
                        line[i-1] = '"'; // then print \
                line[i] = '\0'; // or 0
        }
}

This removes all characters in the line.. what can I do to remove only quotes? Any help would be appreciated...

like image 893
user123 Avatar asked Dec 27 '22 15:12

user123


2 Answers

Your problem is line[i] = '\0'; - it terminates the string.

If you want to remove characters from a C string, you need to hold two indices - one for reading and one for writing, loop over the read index reading each character, and write only the ones you want to keep using the second index.

Something along the lines of:

int j = 0;
for (int i = 0; i < lineLength; i ++) {
            if (line[i] != '"' && line[i] != '\\') { 
                 line[j++] = line[i];
            } else if (line[i+1] == '"' && line[i] == '\\') { 
                 line[j++] = '"';
            } else if (line[i+1] != '"' && line[i] == '\\') { 
                 line[j++] = '\\';
            }
}

//You missed the string termination ;)
if(j>0) line[j]=0;
like image 50
Ofir Avatar answered Jan 09 '23 05:01

Ofir


You are setting the first " character you find to the null character, terminating the string.

Also an aside, but line[i-1] could cause a segmentation fault when i == 0, or it could happen to contain \ in which case the first quote wouldn't be stripped.

Something like this will do what you want:

char *lineWithoutQuotes = malloc(strlen(line));
int i, j;
if(line[0] != '"')
    lineWithoutQuotes[0] = line[0];
for(i = j = 1; i < strlen(line); i++){
    if(line[i] == '"' && line[i-1] != '\\')
        continue;
    lineWithoutQuotes[j++] = line[i];
}
like image 43
Paul Avatar answered Jan 09 '23 05:01

Paul