2024年3月26日发(作者:)
c string replace函数
C语言中的字符串替换函数(replace函数)是一种用于替换字
符串中指定字符或子字符串的函数。它可以在字符串中查找目标字符
或子字符串,并将其替换为指定的字符或子字符串。
在C语言的标准库中,没有直接提供字符串替换函数。但是,可
以通过自己编写函数来实现字符串替换的功能。以下是一种示例的字
符串替换函数:
```c
#include
#include
void replace(char *str, char *orig, char *rep) {
static char buffer[4096];
char *p;
// 查找子串
while ((p = strstr(str, orig)) != NULL) {
// 复制原字符串中的 p 之前的部分到 buffer 中
strncpy(buffer, str, p - str);
buffer[p - str] = '0';
// 追加替换的字符串到 buffer 中
strcat(buffer, rep);
// 追加原字符串中 p 之后的部分到 buffer 中
- 1 -
strcat(buffer, p + strlen(orig));
// 将替换后的字符串复制回 str 中
strcpy(str, buffer);
}
}
```
在上面的代码中,我们定义了一个名为 `replace()` 的函数,
该函数接受三个参数:指向原字符串的指针、指向要替换的子字符串
的指针,以及指向要替换为的字符串的指针。
该函数使用 `strstr()` 函数来查找子字符串,并使用
`strncpy()` 和 `strcat()` 函数来构建替换后的字符串。最后,该
函数使用 `strcpy()` 函数将替换后的字符串复制回原字符串中。
以下是一个示例程序,演示如何使用 `replace()` 函数:
```c
#include
#include
void replace(char *str, char *orig, char *rep);
int main() {
char str[256] = 'hello world';
char orig[256] = 'world';
char rep[256] = 'C language';
- 2 -
replace(str, orig, rep);
printf('%s
', str);
return 0;
}
void replace(char *str, char *orig, char *rep) {
// 实现在上面的代码块中
}
```
在上面的示例程序中,我们将字符串 `'hello world'` 中的子
字符串 `'world'` 替换为 `'C language'`,并将替换后的字符串输
出到控制台。运行该程序后,输出结果为:
```
hello C language
```
这说明我们成功地实现了字符串替换函数。
- 3 -


发布评论