Delete String in C: Remove Characters Easily

In the C language, you can use the following methods to remove a character or delete the entire string from a string.

  1. To remove a specific character from a string, you can use the strcpy() function along with a loop to achieve it. The specific steps are as follows:
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int i, j, len;
    
    printf("Enter a string: ");
    gets(str);
    
    len = strlen(str);
    
    printf("Enter the position of character to be deleted: ");
    scanf("%d", &i);
    
    for (j = i - 1; j < len; ++j) {
        str[j] = str[j + 1];
    }
    
    printf("String after deletion: %s\n", str);
    
    return 0;
}
  1. To delete the entire string, you can use the strcpy() function to copy an empty string to the original string, achieving the effect of clearing it.
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    
    printf("Enter a string: ");
    gets(str);
    
    strcpy(str, "");
    
    printf("String after deletion: %s\n", str);
    
    return 0;
}

The above are two common methods for removing strings, and in specific applications, the appropriate method can be chosen based on actual circumstances.

bannerAds