String matching (naive pattern matching algorithm)

There are two ways to match strings, one is static sequential storage, and the other is dynamic heap storage. Both of these methods are implemented based on sequential lists and linked lists. The naive algorithm of the string is to use the length of the substring to sequentially match the partial characters of the main string of the substring length, so that the characters of the substring length can be compared to the end each time. code show as below:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 255
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

/**
串的顺序存储和链式存储 
由于C语言中有对串直接操作的函数,这只列举一种操作 
朴素模式匹配算法 
*/

//静态定义串的结构体(定长顺序存储)
typedef struct{
    char ch[MaxSize];//存储字符的数组 
    int length;//串的实际长度 
}SString; 

//动态方式定义串的结构体(为了避免存储密度低的问题,让结点存储多个字符) 
typedef struct StringNode{
    char ch[4];//每个结点放四个字符 
    struct StringNode *next;//指针域 
}StringNode,*String; 

//动态定义串的结构体(堆分配存储)
typedef struct{
    char *ch;//按照串长分配储存区,ch指向串的首地址 
    int length;//串的实际长度
}HString; 

//堆分配初始化
void InitHString(HString &S){
    S.ch = (char*)malloc(MaxSize*sizeof(char));
    S.length = 0;
} 

//求子串
bool SubString(SString &Sub,SString S,int pos,int len){
    //子串越界
    if(pos+len-1>S.length){
        return false;
    } 
    for(int i=pos;i<pos+len;i++){
        Sub.ch[i-pos+1] = S.ch[i];
    }
    Sub.length = len;
    return true;
}

//朴素模式匹配算法 
int Index(SString S,SString T){
    int k=1;
    int i=k,j=1;
    while(i<S.length && j<=T.length){
        if(S.ch[i]==T.ch[j]){
            ++i;
            ++j;//继续比较后续字符 
        }else{
            k++;//检查下一个子串 
            i=k;
            j=1;
        }
    }
    if(j>T.length){
        return k;
    }else{
        return 0;
    }
} 

int main(int argc, char** argv) {
    HString S;
    InitHString(S);
    return 0;
}

Guess you like

Origin blog.51cto.com/14049943/2596131