Delete Specific String in C

In C language, to delete a specified string, you can use the strcpy() function and strstr() function. The specific steps are as follows:

  1. Search for the position of the string to be deleted in the original string. You can use the strstr() function to find the first occurrence of the string to be deleted in the original string, returning a pointer to that position if found and NULL if not found.
  2. If the string to be removed is found, use the strcpy() function to move the characters after it to the front, overwriting the string to be deleted. Pointer arithmetic can be used to achieve this.

Here is a sample code:

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

void deleteString(char* str, const char* target) {
    char* pos = strstr(str, target); // 查找要删除的字符串的位置
    if (pos != NULL) {
        strcpy(pos, pos + strlen(target)); // 删除字符串
    }
}

int main() {
    char str[100] = "Hello World";
    const char* target = "World";
    
    deleteString(str, target);
    
    printf("%s\n", str); // 输出:Hello 
    
    return 0;
}

In this example, the string “World” is removed from the string “Hello World”, resulting in the output of “Hello”.

bannerAds