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.
The most common approach to removing a character from a string at the specific index is using slicing. Here's a simple example that returns the new string with character at given index i removed from the string s .
We have removeChar() method that will take a address of string array as an input and a character which you want to remove from a given string. Now in removeChar(char *str, char charToRemove) method our logic is written.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With