写一个简单的c程序,输入两个字符串s1和s2,删除字符串s1中所有与字符串s2匹配的子串,输出s1
时间: 2024-10-10 21:02:16 浏览: 43
当然可以。下面是一个简单的 C 程序,它使用了 `strstr()` 函数来查找 s1 中与 s2 匹配的子串,并通过循环和指针操作来删除这些子串:
```c
#include <stdio.h>
#include <string.h>
void remove_substrings(char *s1, char *s2) {
int len_s1 = strlen(s1);
int len_s2 = strlen(s2);
while (len_s1 >= len_s2) {
char *substring = strstr(s1, s2);
if (substring != NULL) {
// Move the characters after the substring one position forward
memmove(substring + len_s2, substring + len_s2 + 1, len_s1 - substring + 1);
len_s1 -= len_s2; // Reduce the length of s1 by the size of s2
} else {
break; // No more occurrences found, exit the loop
}
}
printf("After removing all occurrences of '%s': %s\n", s2, s1);
}
int main() {
char s1[100], s2[100];
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);
s1[strcspn(s1, "\n")] = '\0'; // Remove newline character from input
printf("Enter string s2: ");
fgets(s2, sizeof(s2), stdin);
s2[strcspn(s2, "\n")] = '\0'; // Remove newline character from input
remove_substrings(s1, s2);
return 0;
}
```
当你运行这个程序并输入两个字符串后,它会输出 s1 中去除所有 s2 子串后的结果。
阅读全文