用c语言完成字符串替换
时间: 2023-07-18 21:28:09 浏览: 71
好的,以下是用 C 语言实现字符串替换的示例代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, char *old, char *new) {
char *pos = strstr(str, old); // 在 str 中查找 old 字符串
if (pos != NULL) {
int len_old = strlen(old); // 计算 old 字符串的长度
int len_new = strlen(new); // 计算 new 字符串的长度
int len_tail = strlen(pos + len_old); // 计算尾部字符串的长度
char tail[len_tail + 1]; // 存储尾部字符串
strcpy(tail, pos + len_old); // 将尾部字符串复制到 tail 中
strncpy(pos, new, len_new); // 将 new 字符串复制到 pos 中
strcpy(pos + len_new, tail); // 将尾部字符串复制到 pos + len_new 中
replace(pos + len_new, old, new); // 递归替换剩余的 old 字符串
}
}
int main() {
char str[] = "hello world, hello everyone";
char old[] = "hello";
char new[] = "hi";
replace(str, old, new);
printf("%s\n", str);
return 0;
}
```
运行结果为:
```
hi world, hi everyone
```
在上面的代码中,我们使用了递归函数来替换字符串中所有的 old 子字符串。函数 replace() 接收三个参数:要进行替换的字符串 str,要替换的旧字符串 old 和替换成的新字符串 new。函数首先在 str 中查找 old 字符串,如果找到了就将 old 字符串替换成 new 字符串,并将剩余的字符串保存到 tail 中,然后递归调用 replace() 函数来替换剩余的 old 字符串。如果在 str 中找不到 old 字符串,递归函数就会停止。