在C語言中,要刪除字符串中的子串,你可以使用以下方法:
strcpy()
和strlen()
函數:#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char sub[] = "World";
char result[strlen(str) + 1];
strcpy(result, str);
int index = strstr(result, sub) - result;
strncpy(result + index, result + index + strlen(sub), strlen(result) - index - strlen(sub));
result[strlen(result)] = '\0';
printf("Original string: %s\n", str);
printf("Modified string: %s\n", result);
return 0;
}
realloc()
和free()
函數:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* remove_substring(char *str, const char *sub) {
char *result = strdup(str);
char *index = strstr(result, sub);
if (index) {
*index = '\0';
realloc(result, strlen(result) - strlen(sub) + 1);
}
return result;
}
int main() {
char str[] = "Hello, World!";
char sub[] = "World";
char *result = remove_substring(str, sub);
printf("Original string: %s\n", str);
printf("Modified string: %s\n", result);
free(result);
return 0;
}
請注意,這些方法都會修改原始字符串。如果你需要保留原始字符串,請創建一個新的字符串來存儲結果。