83 lines
2.0 KiB
C
83 lines
2.0 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**********/
|
||
//动态内存分配数组空间
|
||
result = (char *)malloc(10000);
|
||
p = result;//将数组首地址赋值给一个指针变量用来操作数组
|
||
for(i=0;i<strLen;i++){//主串的下标遍历
|
||
j = 0;//子串的下标遍历
|
||
//判断当前是否找到和主串中是否和子串开头的字符
|
||
if(oldSubstr[j] != str[i]){
|
||
*p++=str[i];//直接存到新字符串
|
||
continue;
|
||
}
|
||
while(oldSubstr[j] != '\0' && oldSubstr[j++] == str[i++]);
|
||
//如果找到和子串相同的元素
|
||
//则一一比较 一直比较到子串到结束符或者到字符不相等
|
||
if(oldSubstr[j] == '\0'){
|
||
//k为主串中子串的起始位置
|
||
k=0;
|
||
while(newSubstr[k] != '\0'){
|
||
*p++ = newSubstr[k++];
|
||
}
|
||
i--;
|
||
}else{//只是前面几个字符匹配 后续并不匹配 则需要从头开始存
|
||
i-=j;
|
||
*p++=str[i];
|
||
}
|
||
}
|
||
*p='\0';
|
||
/*
|
||
字符串:abcabc
|
||
需要替换的子串:a
|
||
替换后的子串:##
|
||
示例输出:##bc##bc
|
||
*/
|
||
|
||
/********** 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;
|
||
}
|