请编写C程序,从s串中删除一个子串t,子串由起始位置start和长度len决定。
时间: 2023-06-12 22:04:42 浏览: 46
以下是一个实现该功能的 C 代码:
```c
#include <stdio.h>
#include <string.h>
void delete_substring(char *s, int start, int len) {
int s_len = strlen(s);
int i, j;
// 移动s串中start+len之后的字符
for (i = start + len; i <= s_len; i++) {
s[i - len] = s[i];
}
// 修改s串长度
s[s_len - len] = '\0';
}
int main() {
char s[100], t[100];
int start, len;
printf("请输入原字符串s:");
gets(s);
printf("请输入要删除的子串t:");
gets(t);
printf("请输入子串t的起始位置:");
scanf("%d", &start);
printf("请输入子串t的长度:");
scanf("%d", &len);
// 查找子串t在s中的位置
char *p = strstr(s, t);
if (p != NULL) {
int index = p - s;
if (index == start) {
// 调用删除子串函数
delete_substring(s, start, len);
printf("删除后的字符串为:%s\n", s);
} else {
printf("子串t不在字符串s的起始位置!");
}
} else {
printf("子串t不在字符串s中!");
}
return 0;
}
```
注意:这里使用了 `gets()` 函数,但它已经被标记为不安全的函数,建议使用 `fgets()` 替代。另外,该代码只处理了子串在字符串开头的情况,如果子串在字符串中间或结尾的情况,需要进行相应的修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)