How to remove the character at a given index from a string in C?

Try this :

void removeChar(char *str, char garbage) {

    char *src, *dst;
    for (src = dst = str; *src != '\0'; src++) {
        *dst = *src;
        if (*dst != garbage) dst++;
    }
    *dst = '\0';
}

Test program:

int main(void) {
    char* str = malloc(strlen("abcdef")+1);
    strcpy(str, "abcdef");
    removeChar(str, 'b');
    printf("%s", str);
    free(str);
    return 0;
}

Result:

>>acdef

memmove can handle overlapping areas, I would try something like that (not tested, maybe +-1 issue)

char word[] = "abcdef";  
int idxToDel = 2; 
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

Before: "abcdef"

After: "abdef"

Tags:

C

String