char *ReplaceString(char * str, char * s1, char * s2)
时间: 2023-07-23 13:28:42 浏览: 53
这是一个用于替换字符串中指定子字符串的函数。函数接受三个参数:原始字符串指针,需要替换的子字符串指针和替换成的子字符串指针。函数返回一个指向新字符串的指针。
下面是函数的代码实现:
```c
char *ReplaceString(char * str, char * s1, char * s2) {
char *result;
int i, cnt = 0;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
// 计算需要替换的子字符串的数量
for (i = 0; str[i] != '\0'; i++) {
if (strstr(&str[i], s1) == &str[i]) {
cnt++;
i += s1_len - 1;
}
}
// 为新字符串分配内存
result = (char *)malloc(i + cnt * (s2_len - s1_len) + 1);
i = 0;
while (*str) {
// 如果找到需要替换的子字符串,则将其替换为新字符串
if (strstr(str, s1) == str) {
strcpy(&result[i], s2);
i += s2_len;
str += s1_len;
}
else
result[i++] = *str++;
}
result[i] = '\0';
return result;
}
```
使用示例:
```c
char str[] = "The quick brown fox jumps over the lazy dog";
char *result = ReplaceString(str, "fox", "cat");
printf("%s", result);
free(result);
```
该示例会将字符串中的“fox”替换为“cat”,并输出结果:“The quick brown cat jumps over the lazy dog”。函数会动态分配内存,因此使用完毕后需要使用free()函数释放内存。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)