How to remove a character from a string in the C language?

To remove a character from a string in C programming, one common approach is to use the string handling function strcpy() to copy the part of the string after the character to be deleted to the original string’s position, thus overwriting the character to be deleted.

Here is a sample code for removing a character from a string.

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

void deleteChar(char *str, char c) {
    int i, j;
    for (i = 0, j = 0; str[i] != '\0'; i++) {
        if (str[i] != c) {
            str[j++] = str[i];
        }
    }
    str[j] = '\0';
}

int main() {
    char str[] = "Hello, World!";
    char c = 'o';
    
    printf("Original string: %s\n", str);
    
    deleteChar(str, c);
    
    printf("String after deleting '%c': %s\n", c, str);
    
    return 0;
}

The deleteChar() function in the code above takes a string and a character to delete as parameters. It then loops through the string, copying any character that is not equal to the character to be deleted to the original string’s position. Finally, it adds a null terminator ‘\0’ to indicate the end of the new string.

When the above code is executed, it will produce:

Original string: Hello, World!
String after deleting 'o': Hell, Wrld!
广告
Closing in 10 seconds
bannerAds