Favolas Favolas - 4 months ago 7
C Question

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

How do I remove a character from a string?

If I have the string

"abcdef"
and I want to remove
"b"
how do I do that?

Removing the first character is easy with this code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char word[] = "abcdef";
char word2[10];

strcpy(word2,&word[1]);

printf("%s\n", word2);

return 0;
}


and

strncpy(word2,word,strlen(word)-1);


will give me the string without the last character, but I still didn't figure out how to remove a char in the middle of a string.

Answer

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"