首页 > 编程语言 > 详细

字符串的朴素模式匹配算法

时间:2016-12-11 12:38:18      阅读:214      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>
#include <string.h>

//返回第一个子串在主串的位置,找不到返回-1

int StrMatch(char *source, char *match){
    int slen=strlen(source);
    int mlen=strlen(match);
    int i=0,j=0;
    
    
    while(i<slen && j<mlen){//当主串或者子串全部匹配完,就退出循环
        if(source[i] == match[j]){//逐个比较,匹配就比较下一个
            ++i;
            ++j;
        }else{//不匹配就重新回到刚开始的下一个位置
            i = i-j+1;
            j = 0;
        }
    }

    if(j == mlen){//说明子串全部都匹配成功,返回子串在主串的位置
        return  (i-j);
    }else{
        return -1;
    }
    
}

void main(){

    char str[] = "hello, tom ,how are you!";
    char match[] = " tom ";
    int result;

    result = StrMatch(str,match);
    printf("-->%d\n",result);

}

 

字符串的朴素模式匹配算法

原文:http://www.cnblogs.com/wwzyy/p/6159259.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!