字符串的比较

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];
            }
    }
}

你可能感兴趣的:(字符串的比较)