编写一个函数: char *ReplaceString(char * str, char * s1, char * s2); 该函数用s2替换str中的s1,函数返回替换后的字符串的指针。
时间: 2023-08-07 14:02:53 浏览: 118
好的,以下是我为您编写的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ReplaceString(char * str, char * s1, char * s2) {
int old_len = strlen(s1);
int new_len = strlen(s2);
int count = 0;
char *p, *q, *r;
p = str;
while ((q = strstr(p, s1)) != NULL) {
count++;
p = q + old_len;
}
int len = strlen(str) + (new_len - old_len) * count + 1;
r = (char *) malloc(len * sizeof(char));
p = str;
q = r;
while ((p = strstr(p, s1)) != NULL) {
strncpy(q, str, p - str);
q += p - str;
strncpy(q, s2, new_len);
q += new_len;
p += old_len;
str = p;
}
strcpy(q, str);
return r;
}
int main() {
char *str = "Hello world, this is a test string.";
char *s1 = "test";
char *s2 = "replacement";
char *result = ReplaceString(str, s1, s2);
printf("%s\n", result);
free(result);
return 0;
}
```
这个函数的实现方法是先遍历一遍字符串,计算出需要替换的次数,然后根据替换前后的字符串长度差,计算出最终字符串的长度,再分别从原字符串和目标字符串中逐个字符地拷贝到新字符串中,最后返回新字符串的指针。
阅读全文