编写程序,输入字符串s、s的子串s1、字符串s2。要求将s中所有的子串s1替换为s2,输出替换后的字符串。上述字符串中不含空格,替换后字符串的长度不超过100 要求 (1)在函数中进行替换操作,在主函数中输出 (2)使用指针进行操作,字符数组使用动态内存分配管理,不要使用字符串库函数 示例: 输入: abcdeacdfg cd 1234 输出: ab1234ea1234fg
时间: 2024-02-09 22:11:25 浏览: 122
以下是一个实现该功能的C语言程序,使用了指针和动态内存分配:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace(char *s, char *s1, char *s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
int len = strlen(s);
int count = 0; // 统计子串出现的次数
char *p = s;
// 统计子串出现的次数
while ((p = strstr(p, s1)) != NULL) {
count++;
p += len1;
}
// 计算替换后的字符串长度
int new_len = len + count * (len2 - len1);
// 分配新的字符串内存
char *new_s = (char *) malloc(sizeof(char) * (new_len + 1));
if (new_s == NULL) {
printf("Error: out of memory.\n");
return;
}
// 进行替换操作
char *p1 = s;
char *p2 = new_s;
while (*p1 != '\0') {
if (strncmp(p1, s1, len1) == 0) {
strncpy(p2, s2, len2);
p1 += len1;
p2 += len2;
} else {
*p2 = *p1;
p1++;
p2++;
}
}
*p2 = '\0';
// 释放原字符串内存,使用替换后的字符串内存
free(s);
s = new_s;
// 输出替换后的字符串
printf("%s\n", s);
}
int main() {
char s[101], s1[101], s2[101];
// 读取输入字符串
printf("Input a string: ");
scanf("%s", s);
printf("Input a substring to replace: ");
scanf("%s", s1);
printf("Input a replacement string: ");
scanf("%s", s2);
// 进行替换操作
replace(s, s1, s2);
return 0;
}
```
该程序中,`replace()`函数用于进行替换操作,使用了指针和动态内存分配。在`main()`函数中,首先读取输入字符串,然后调用`replace()`函数进行替换操作,最后输出替换后的字符串。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![](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://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)