在C語(yǔ)言中,要從字符串中刪除子字符串,你可以使用以下方法:
strcpy()
和strlen()
函數(shù)memmove()
函數(shù)下面是兩種方法的示例代碼:
方法1:使用strcpy()
和strlen()
函數(shù)
#include <stdio.h>
#include <string.h>
void remove_substring(char *str, const char *sub) {
char result[strlen(str) + 1];
char *src, *dst;
src = str;
dst = result;
while (*src != '\0') {
if (strncmp(src, sub, strlen(sub)) != 0) {
*dst++ = *src;
}
src++;
}
*dst = '\0';
strcpy(str, result);
}
int main() {
char str[] = "Hello, I am a C programming assistant.";
const char *sub = "C programming";
printf("Original string: %s\n", str);
remove_substring(str, sub);
printf("After removing substring: %s\n", str);
return 0;
}
方法2:使用memmove()
函數(shù)
#include <stdio.h>
#include <string.h>
void remove_substring(char *str, const char *sub) {
char *src, *dst;
size_t sub_len = strlen(sub);
src = str;
dst = str;
while (*src != '\0') {
if (strncmp(src, sub, sub_len) != 0) {
dst = src;
}
src++;
}
*dst = '\0';
}
int main() {
char str[] = "Hello, I am a C programming assistant.";
const char *sub = "C programming";
printf("Original string: %s\n", str);
remove_substring(str, sub);
printf("After removing substring: %s\n", str);
return 0;
}
請(qǐng)注意,這兩種方法都會(huì)修改原始字符串。如果你需要保留原始字符串,可以創(chuàng)建一個(gè)新的字符串來(lái)存儲(chǔ)結(jié)果。