#include <stdio>
/// 字符串匹配,在主串中删除子串
int main()
{
int length_str( char *str);//声明子函数
char str1[512]={0}, str2[512]={0};
scanf("%s", str1); //主串
scanf("%s", str2); //子串
int len1 = length_str(str1);
int len2 = length_str(str2);
int count = 0; //匹配次数
int index[10]={0}; //子串在主串中的起始匹配位置
for (int i=0; i< len1-len2+1; i++) //计算匹配信息
{
int k=0;//一次匹配过程中,子串在主串内匹配成功的字符数
for (int j=0; j<len2; j++)
{
if ( str1[i+j] == str2[j] )
{
k++;
}
if (k==len2) //匹配成功,匹配次数++,记录匹配信息
{
count++;
index[count-1] = i;
}
}
}
for (; count>0; count--) //根据匹配信息从主串删除子串
{
for (int m = index[count-1]; m<= len1-1-len2; m++)
{
str1[ m ] = str1[ m + len2 ];
}
len1 -= len2;
}
str1[len1] = '\0';
printf("Result: %s", str1);
return 0;
}
//子函数:求字符串长度
int length_str( char *str)
{
int len = 0;
while( *str != '\0')
{
len++;
str++;
}
return len;
}
KMP算法的C++代码:
……ToBeContinued
二者的比较:
……ToBeContinued