Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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.

like image 547
Favolas Avatar asked Mar 28 '11 10:03

Favolas


People also ask

How do I remove a character from a specific index?

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 .

How do you remove a given character from string in C?

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.


2 Answers

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"

like image 60
stacker Avatar answered Sep 20 '22 14:09

stacker


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 
like image 40
Fabio Cabral Avatar answered Sep 19 '22 14:09

Fabio Cabral