KMP算法2

时间:2020-12-21 16:57:28

给定一个主串s,一个子串sub,将主串中的所有子串替换成replaceStr,并将最终结果输出来。

 #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int next[];
void getNext(char pattern[])
{
int k=-,len=strlen(pattern),j=;
next[]=-;
while(j<len){
if(k==-||pattern[k]==pattern[j]){
k++;j++;
next[j]=k;
}else{
k=next[k];
}
}
} int KMP(char text[],char pattern[])
{
int i=,j=,lent=strlen(text),lenp=strlen(pattern);
getNext(pattern);
while(i<lent&&j<lenp){
if(j==-||text[i]==pattern[j]){
i++;j++;
}else{
j=next[j];
}
}
if(j==lenp)
return i-j;
return -;
} char* strSub(char* s,int pos,int length)//字符串截取函数
{
char *sub=(char *)calloc(length,sizeof(char));
int i=pos;
int count=;
while(count<length)
{
sub[count]=s[i];
i++;
count++;
}
sub[count]='\0';
return sub;
} char* strReplace(char* s,char* sub,char* replaceStr)//字符串替换函数
{
int end;
char* temp1;
char* temp2;
int begin=;
int subLength=strlen(sub);
end=KMP(s,sub);
while(end!=-)
{
temp1=strSub(s,begin,end-begin);
temp2=strSub(s,end+subLength,strlen(s)-(end+subLength));
s=strcat(temp1,replaceStr);
s=strcat(s,temp2);
end=KMP(s,sub);
}
return s;
}
int main()
{
char s[],sub[],replaceStr[];
char *answer=(char *)calloc(,sizeof(char));
printf("input s:\n");
gets(s);
printf("input sub:\n");
gets(sub);
printf("input replaceStr:\n");
gets(replaceStr);
answer=strReplace(s,sub,replaceStr);
printf("final str is:\n");
puts(answer);
return ;
}