//串的简单模式匹配
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 30
typedef struct
{
char data[MAXSIZE];
int len;
}SeqString; //顺序串类型
int StrIndex_BF(SeqString *S, SeqString *T) //简单模式匹配
{
int i = 0, j = 0;
while (i < S->len && j < T->len)
{
if (S->data[i] == T->data[j])
{
i++;
j++;
}
else
{
i = i - j + 1; //将指针i 调至主串S 新一趟开始的匹配位置
j = 0; //将指针j 调至子串T 的第一个字符位置
}
}
if (j >= T->len)
{
return (i - T->len); //
}
else
{
return (-1);
}
}
void gets1(SeqString *p) //给p->data 数组输入一个字符串
{
int i = 0;
char ch;
p->len = 0;
scanf("%c", &ch);
while (ch != '\n')
{
p->data[i++] = ch;
p->len++;
scanf("%c", &ch);
}
p->data[i++] = '\0';
}
int main()
{
int i;
SeqString *s, *t;
s = (SeqString *)malloc(sizeof(SeqString)); //生成主串s 的存储空间
t = (SeqString *)malloc(sizeof(SeqString)); //生成子串t 的存储空间
printf("Input main string S:\n");
gets1(s);
printf("Output main string S:\n");
puts(s->data); //输出主串s
printf("Input substring T:\n");
gets1(t);
printf("Output substring T:\n");
puts(t->data); //输出子串t
i = StrIndex_BF(s, t); //对主串s 和子串t 进行模式匹配
if (i == -1)
{
printf("No match string!\n");
}
else
{
printf("Match position: %d\n", i + 1); //匹配成功,输出子串t 在主串s中的起始位置
}
return 0;
}
串简单模式匹配
最新推荐文章于 2019-02-19 18:53:20 发布