Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C deleting char in string

Now I’m using this code to delete some char in a string.

void eliminate(char *str, char ch){
    for(; *str != '\0';str++){
        if(*str == ch){
            strcpy(str, str+1);
            str--;
        }
    }
}

In the char *str there are some strings like

"sll $6, $5, 16"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

After deleting "$", the string looks like this.

"sll 6, 5, 16"

But after deleting ",", the string became very strange.

"sll 6 5 6"

Is there any problem with the code above? And also, it only happens in Linux and online GDB. VS code in my window laptop eliminates the targeted char very well.

>Solution :

As pointed out in comments strcpy() is not safe when coping data with overlapping memory blocks. memmove(dst, src, len) is the alternative which uses an auxiliary buffer in case of src & dst memory overlaps.

You can simply skip the character to eliminate in a loop:

#include <stdio.h>

void drop_char (char *str, char ch) {
    if (!str) return;

    for(char* cp = str; 1 ; ) {
        if(*cp != ch)
            *str++ = *cp;
        if ('\0' == *cp++)
            break;
    }
}

int main () {
    char str [] = "sll     $6, $5, 16";
    printf ("Original   : [%s]", str);

    drop_char(str, '$');
    printf ("\nDropping $ : [%s]", str);

    drop_char(str, ',');
    printf ("\nDropping , : [%s]", str);

    printf ("\n");

    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading