【C/C++】字符串匹配,从主串中删除子串并打印

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值