串简单模式匹配
来源:互联网 发布:知乎 发现 编辑:程序博客网 时间:2024/06/07 15:10
//串的简单模式匹配#include <stdio.h>#include <stdlib.h>#define MAXSIZE 30typedef 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); //输出子串ti = 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;}
阅读全文