c语言字符串相同多个子串全部替换
时间: 2024-11-13 17:23:12 浏览: 38
在C语言中,如果需要在一个字符串中查找并替换所有相同的子串,可以使用`strstr()`函数来遍历原字符串,找到每个子串的位置,然后用`strcpy()`和`strcat()`函数替换。这里是一个简单的示例,假设我们有一个原始字符串`str`和一个要替换的子串`old_str`以及替换的新子串`new_str`:
```c
#include <stdio.h>
#include <string.h>
void replace_all(char *str, const char *old_str, const char *new_str) {
size_t old_len = strlen(old_str);
while ((size_t pos = strstr(str, old_str)) != NULL) {
// 将从pos开始到end的所有字符复制到新位置
char temp[old_len + 1]; // 用于临时存储旧子串
strncpy(temp, str, pos - str); // 复制到temp
temp[pos - str] = '\0'; // 结束字符串
// 添加新子串
strcat(temp, new_str);
// 更新原字符串
memmove(str + old_len, str + pos, strlen(str) - pos + 1); // 移动剩余部分
strcpy(str, temp); // 将新内容复制回str
}
}
int main() {
char str[] = "Hello, world! This is a sample string.";
const char *old_str = "sample";
const char *new_str = "example";
replace_all(str, old_str, new_str);
printf("Modified string: %s\n", str);
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)