写一个在内存中可以替换长度不相等的字符串的函数
时间: 2024-01-22 14:20:53 浏览: 30
下面是一个在内存中替换长度不相等的字符串的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace_string(char *source, char *pattern, char *replacement) {
int source_len = strlen(source);
int pattern_len = strlen(pattern);
int replacement_len = strlen(replacement);
// 计算新字符串的长度
int new_len = source_len;
int count = 0;
char *s = source;
while ((s = strstr(s, pattern)) != NULL) {
count++;
s += pattern_len;
}
new_len += (replacement_len - pattern_len) * count;
// 重新分配内存空间
char *new_str = (char *) malloc(sizeof(char) * (new_len + 1));
if (new_str == NULL) {
printf("内存不足,无法替换字符串!\n");
return;
}
// 遍历原字符串,将匹配到的模式替换为新字符串
char *p = source;
char *q = new_str;
while (*p != '\0') {
if (strstr(p, pattern) == p) {
strcpy(q, replacement);
p += pattern_len;
q += replacement_len;
} else {
*q++ = *p++;
}
}
*q = '\0';
// 将新字符串拷贝回原字符串
strcpy(source, new_str);
free(new_str);
}
int main() {
char source[] = "Hello, world!";
char pattern[] = "world";
char replacement[] = "ChitChat";
replace_string(source, pattern, replacement);
printf("%s\n", source);
return 0;
}
```
在这个函数中,我们先计算新字符串的长度,然后重新分配内存空间,遍历原字符串并将匹配到的模式替换为新字符串。最后,将新字符串拷贝回原字符串并释放新字符串的内存空间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)