字符串的比较

BF算法

#include "stdio.h"
#include "string.h"
#include "stdbool.h"
//判断是否为子串

int main(void)
{
    char *str1,*str2;
    int base = 0,A1 = 0,A2 = 0,Len1,Len2;
    bool flag = 0;
    str1 = (char*)malloc(100*sizeof(char));
    str2 = (char*)malloc(100*sizeof(char));
	//指针动态申明存储空间↑
    printf("母串为:");
    scanf("%s",str1);
    getchar();
    printf("子串为:");
    scanf("%s",str2);
    Len1 = strlen(str1);
    Len2 = strlen(str2);
    printf("母串长度为:%d,子串长度为:%d\n",Len1,Len2);

    while ((Len1 - A1)>0 && (Len2 - A2)>0)
    {
        flag = 0;
        if(str1[A1] == str2[A2])
        {
            A1++;
            A2++;
            continue;
        }
        else
        {
            base++;
            A1 = A1 - A2 + 1;
            A2 = 0;
            flag = 1;
        }
    }

    if(flag)
    {
        printf("\n非子串\n");

    }else
    {
        printf("\n是子串,从%d位开始相等\n",base);
    }
    return 0;
}

KMP算法及实现(.c)

#include "stdio.h"
#include "string.h"
#include "math.h"
#include "stdbool.h"
#include "time.h"
#include "stdarg.h"

typedef char* string;
int IndexKmp(string s,string t,int pos);
void GetNext( string T, int *next);

int main(void)
{
    char str_0[10] = " abcdefg";
    char str_1[5] = " abcd";
    str_0[0] = 7;
    str_1[0] = 4;
    int result = 0;

    result = IndexKmp(str_0,str_1,1);
    printf("%d \n",result);

    return 0;
}
//s母串,t子串,从哪里开始比较
int IndexKmp(string s,string t,int pos)
{
    int i = pos;
    int j = 1;
    int next[255];

    GetNext(t,next);

    while(i <= s[0] && j <= t[0])//数组第一个保存该数组的长度
    {
        if(s[i] == t[j] || j == 0)
        {
            i++;
            j++;
        }else
        {
            j = next[j];//回溯到next数组指向的位置
        }
    }
    if(j > t[0])
    {
        return i - t[0];//从第几个返回
    }else
    {
        return -1;
    }
}

void GetNext( string T, int *next)
{
    int j = 0;
    int i = 1;
    next[1] = 0;

    while( i < T[0] )
    {
            if( 0 == j || T[i] == T[j] )
            {
                    i++;
                    j++;
                    next[i] = j;
            }
            else
            {
                    j = next[j];
            }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值