c语言字符串替换指针
时间: 2023-12-12 10:35:12 浏览: 124
以下是一个使用指针进行C语言字符串替换的示例代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;
if(!(p = strstr(str, orig))) // 在str中查找orig
return;
strncpy(buffer, str, p-str); // 复制p之前的部分到buffer中
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig)); // 将rep和p之后的部分连接到buffer中
strcpy(str, buffer); // 将buffer复制回str中
replace(str, orig, rep); // 递归调用,继续查找并替换
}
int main()
{
char str[] = "hello world, world!";
char orig[] = "world";
char rep[] = "earth";
replace(str, orig, rep);
printf("%s\n", str); // 输出:hello earth, earth!
return 0;
}
```
该示例代码中,`replace`函数使用指针实现了字符串替换功能。它首先在`str`中查找`orig`,如果找到了,就将`orig`替换为`rep`。然后,它使用递归调用,继续查找并替换,直到`str`中不再包含`orig`为止。