在一篇英文文章中查找指定的人名,人名使用二十六个英文字母(可以是大写或小写)、
空格以及两个通配符组成(* ?),
通配符“*”表示零个或多个任意字母,
空格以及两个通配符组成(* ?),
通配符“*”表示零个或多个任意字母,
通配符“?”表示一个任意字母。如:“J* Smi??” 可以匹配“John Smith” .
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
char* search(char* content, char* searchStr) {
if (!content || !searchStr) {
return NULL;
}
char *result = (char*) calloc(sizeof(char), SIZE);
int i = 0, j = 0, k = 0;
char temp = *(searchStr + k);
while (*(content + j) != '\0') {
//遇到*
if (temp == '*') {
//取出*后的字符
char next = *(searchStr + k + 1);
//无论*在末尾还是中间,相等时退出
while (*(content + j) != next) {
//文本已结束,匹配串未结束
if (*(content + j) == '\0') {
break;
}
//记录当前字符
*(result + (i++)) = *(content + j);
++j;
}
//下一个匹配符
temp = *(searchStr + (++k));
} else if (temp == '?') { //遇到?
//直接放入结果集
*(result + (i++)) = *(content + j);
temp = *(searchStr + (++k));
j++;
} else {
//字母空格
if (temp == *(content + j)) {
//相等放入
*(result + (i++)) = *(content + j);
temp = *(searchStr + (++k));
} else {
//不等时重置
result = (char*) calloc(sizeof(char), SIZE);
k = 0;
i = 0;
temp = *(searchStr + k);
}
j++;
}
//完整匹配
if (temp == '\0') {
*(result + i) = '\0';
puts(result);
result = (char*) calloc(sizeof(char), SIZE);
k = 0;
i = 0;
temp = *(searchStr + k);
}
}
}