2025-02-25 08:30:32 +08:00

52 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 动态分配内存以存储替换后的字符串
char* replaceSubstring(const char *str, const char *oldSubstr, const char *newSubstr) {
int strLen = strlen(str);
int oldLen = strlen(oldSubstr);
int newLen = strlen(newSubstr);
int count=0, i, j, k;
char *result, *p;
/**********Program**********/
/********** End **********/
return result;
}
int main() {
char str[10000];
char oldSubstr[100];
char newSubstr[100];
char *replacedStr;
// 获取用户输入
printf("【请输入原字符串:】");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0; // 去除换行符
printf("【请输入要替换的子串:】");
fgets(oldSubstr, sizeof(oldSubstr), stdin);
oldSubstr[strcspn(oldSubstr, "\n")] = 0; // 去除换行符
if (strstr(str, oldSubstr) == NULL) {
printf("原字符串不包含所输入的子串。\n");
return 0;
}
printf("【请输入替换后的子串:】");
fgets(newSubstr, sizeof(newSubstr), stdin);
newSubstr[strcspn(newSubstr, "\n")] = 0; // 去除换行符
replacedStr = replaceSubstring(str, oldSubstr, newSubstr);
printf("【示例输出:】%s\n", replacedStr);
// 释放动态分配的内存
free(replacedStr);
return 0;
}