c语言串replace函数代码
时间: 2023-08-15 20:06:18 浏览: 39
以下是一个简单的 C 语言实现的 replace 函数代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, char *sub_str, char *new_str) {
int len_str = strlen(str);
int len_sub_str = strlen(sub_str);
int len_new_str = strlen(new_str);
int i, j = 0;
char temp[len_str];
for (i = 0; i <= len_str - len_sub_str; i++) {
if (strncmp(str + i, sub_str, len_sub_str) == 0) {
strcpy(temp + j, new_str);
j += len_new_str;
i += len_sub_str - 1;
}
else {
temp[j++] = str[i];
}
}
temp[j] = '\0';
strcpy(str, temp);
}
int main() {
char str[] = "Hello, world!";
char sub_str[] = "world";
char new_str[] = "everyone";
replace(str, sub_str, new_str);
printf("%s\n", str);
return 0;
}
```
这个函数的功能是将字符串 str 中的子字符串 sub_str 替换为字符串 new_str。函数中使用了一个临时字符数组 temp 来存储替换后的字符串。具体实现过程是:遍历字符串 str,如果发现子字符串 sub_str,则将 new_str 复制到 temp 中,否则将 str 中的字符复制到 temp 中。最后将 temp 中的字符串复制回 str 中。