OneBite.Dev - Coding blog in a bite size

remove a character from a string in C

Code snippet on how to remove a character from a string in C

  char *remove_char(char *str, char garbage) {

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

This code uses pointers to remove a character from a string in C. The ‘src’ and ‘dst’ pointer are set up to be equal to ‘str’. The loop then runs through the characters of the string one by one and assigns each character to dst. The if statement checks if each character is equal to the character we are trying to remove - if not, the character is copied from ‘src’ to ‘dst’ and the ‘dst’ pointer is incremented by one. When the loop has completed, the end of the string is marked with a end of string character - ‘\0’. The string is then returned.

c