版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21385857/article/details/51105414
4.1采用顺序结构存储串,编写一个实现串通配符匹配的算法pattern_index(),其中的通配符只有“?”,它可以和任一字符匹配成功,例如,pattern_index("?re","there are"),返回的结果是2。
代码:
#include <iostream>
#include <malloc.h>
#include <cstring>
#include <cstdio>
using namespace std;
#define MaxSize 100
typedef struct
{
char data[MaxSize];
int length;
} SqString;
void StrAssign(SqString *&s,char a[])
{
s=(SqString *)malloc(sizeof(SqString));
int i;
for(i=0; a[i]!='\0'; i++)
{
s->data[i]=a[i];
}
s->length=i;
}
int pattern_index(char c[],SqString *s)
{
int count=0;
for(int i=0; i<s->length; i++)
{
int j,k;
for(j=i,k=0; k<strlen(c)&&(s->data[j]==c[k]||c[k]=='?'); j++,k++); //循环完看k的值,也就是看是否能循环完子串的长度
if(k==strlen(c))
count++;
}
if(count!=0)
return count;
else
return -1;
}
int main()
{
SqString *s;
char ch1[100],ch2[100];
gets(ch1);
gets(ch2);
StrAssign(s,ch1);
cout<<pattern_index(ch2,s)<<endl;
return 0;
}