c语言字符串全局替换特定字符串
时间: 2023-04-03 13:04:41 浏览: 111
可以使用循环和字符串函数来实现全局替换特定字符串,具体步骤如下:
1. 定义原字符串和要替换的字符串;
2. 使用循环遍历原字符串,找到要替换的字符串;
3. 使用字符串函数将要替换的字符串替换成新的字符串;
4. 将替换后的字符串赋值给原字符串;
5. 重复步骤2-4,直到原字符串中没有要替换的字符串。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, const char *old, const char *new) {
int len1 = strlen(old);
int len2 = strlen(new);
char *p = str;
while ((p = strstr(p, old)) != NULL) {
memmove(p + len2, p + len1, strlen(p + len1) + 1);
memcpy(p, new, len2);
p += len2;
}
}
int main() {
char str[] = "hello world, world is beautiful!";
const char old[] = "world";
const char new[] = "universe";
replace(str, old, new);
printf("%s\n", str);
return 0;
}
```
输出结果为:
```
hello universe, universe is beautiful!
```
希望能对你有所帮助!