#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Replace(char *s,char *t,char *v) //对s采用char s[]等同于char *s 传递值 *为取消引用
{
if(strlen(t)!=strlen(v))
{ printf("The length of the two string you entered are not the same \n"); exit(0); }
int slen=strlen(s);
int tlen=strlen(t);
int i=0,j=0;
while(i<slen) //没到达s的末尾则比较
{
while(i<slen && j<tlen)
{
if(s[i]==t[j]) {i++; j++;} //如果相同则i,j加1
else {i=i-j+1; j=0;} //否则i退回到i-j+1
}
if(j>=tlen) //如果找到子串则进行替换
{
int k=i-tlen;
for(j=0;j<tlen;k++,j++)
{s[k]=v[j];}
}
j=0; //对t的指针以0赋值 从新开始比较
if(i>=slen)
{printf("主串中没有输入的子串\n");exit(0);}
}
}
int main()
{
char str[50],sstr[50],rstr[50];
printf("Enter the main string please\nthen I will find the place where the second string in it\n");
scanf("%s",str);
puts(str);
printf("\nEnter the sub string, and the the string you want to replace :\n");
scanf("%s%s",sstr,rstr);
Replace(str,sstr,rstr);
printf("%s\n替换成功\n",str);
return 0;
}
温馨提示:答案为网友推荐,仅供参考