编写c语言程序:编写一个函数实现从源字符串中查找目标字符串,并进行替换
时间: 2024-03-03 14:48:19 浏览: 99
好的,以下是一个简单的 C 语言函数,可以实现从源字符串中查找目标字符串,并进行替换:
```c
#include <stdio.h>
#include <string.h>
void replace(char *src, char *target, char *replacement) {
int target_len = strlen(target);
int replacement_len = strlen(replacement);
char buffer[1024];
char *p;
while ((p = strstr(src, target)) != NULL) { // 查找目标字符串
strncpy(buffer, src, p - src); // 复制目标字符串前面的部分
buffer[p - src] = '\0';
strcat(buffer, replacement); // 拼接替换字符串
strcat(buffer, p + target_len); // 拼接目标字符串后面的部分
strcpy(src, buffer); // 复制替换后的字符串
}
}
int main() {
char src[1024] = "hello, world!";
char target[64] = "world";
char replacement[64] = "ChitChat";
replace(src, target, replacement);
printf("%s\n", src); // 输出替换后的字符串
return 0;
}
```
这个程序中的 `replace` 函数接受三个参数:源字符串 `src`、目标字符串 `target` 和替换字符串 `replacement`。函数中使用了 C 语言标准库中的 `strstr` 函数来查找目标字符串,并使用 `strncpy`、`strcat` 和 `strcpy` 等函数来进行字符串操作,最终将替换后的字符串复制给了源字符串 `src`。在 `main` 函数中,我们可以调用 `replace` 函数来实现字符串的替换。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)