您的位置:首页 > 其它

用一道例题来分享两种匹配字符串的算法!

2016-11-29 23:14 197 查看
输入一个字符串,同时输入帧头和帧尾(可以是多个字符),将该字符串中合法的帧识别出来,

提示 :帧头和帧尾分别是 head 和 tail 字符串 "asdheaddjfvjdhtail"中headdjfvjdhtail是合法帧,
主函数.c文件

#include<stdio.h>
#include<string.h>

#define MAX_SIZE 100

int main()
{
    int i;
    int hd;
    int tl;

    int match(char *f,char *p,int len);

    char father[MAX_SIZE];
    char head[MAX_SIZE];
    char tail[MAX_SIZE];
    

printf("please input the father string:\n");
    scanf("%s",father);

    printf("please input the head string:\n");
    scanf("%s",head);

    printf("please input the tail string:\n");
    scanf("%s",tail);
    printf("%s\n",head);
    

hd = match(father,head,strlen(head));
    tl = match(father,tail,strlen(tail));

    printf("%s\n",father);

    printf("%s\n",head);

    printf("%s\n",tail);
    for(i = hd;i < tl + strlen(tail);i++)
    {
        printf("%c",father[i]);
    }
    printf("\n");

    return 0;
}
匹配算法:

 

#include<stdio.h>
#include<string.h>

int match(char *f,char *p,int len)
{
    int i;
    int k = 0;

    char temp[20];

    while(*f != '\0')
    {
        if((*f) == (*p))
 {
     for(i = 0;i < len;i++)
     {
         temp[i] = *(f + i);
     }
     temp[i] = '\0';
 }
 if(strcmp(temp,p) == 0)
 {
     break;
 }
        k++;
        f++;
    }
    return k;
}

再介绍一种匹配算法:

int mystrncom(char *f,char *s,int len)
{
    int i;
    for(i = 0;i < len;i++)
    {
        if(*(f + i) != *(s + i))
 {
     return -1;
 }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: