Search code examples
ccharc-stringsfunction-definitionfunction-declaration

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"

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;
    }