c语言编写一个函数char*sbstr(char*p )
时间: 2024-03-21 18:34:39 浏览: 59
```c
#include <stdio.h>
#include <string.h>
char* sbstr(char* p, char* t1, char* t2) {
char* last_occurrence = strrchr(p, t1[0]); // 找到t1最后一次出现的位置
if (last_occurrence != NULL) {
int t1_len = strlen(t1);
int t2_len = strlen(t2);
int p_len = strlen(p);
int new_len = p_len - t1_len + t2_len; // 新串的长度
char* new_str = malloc(new_len + 1); // 分配新串的内存空间
strncpy(new_str, p, last_occurrence - p); // 复制t1之前的部分到新串中
strcpy(new_str + (last_occurrence - p), t2); // 复制t2到新串中
strcpy(new_str + (last_occurrence - p) + t2_len, last_occurrence + t1_len); // 复制t1之后的部分到新串中
return new_str;
}
return p;
}
int main() {
char s[100];
char t1[100];
char t2[100];
char w[100];
printf("请输入s所指字符串:");
scanf("%s", s);
printf("请输入t1所指字符串:");
scanf("%s", t1);
printf("请输入t2所指字符串:");
scanf("%s", t2);
char* result = sbstr(s, t1, t2);
strcpy(w, result);
printf("替换后的新串:%s\n", w);
return 0;
}
```
阅读全文