在原字符串中查找子字符串,子字符串中允许使用通配符'?',代表任意一个字符 * 例如子字符串为"?s", 原字符串为"This is a thesis." 则返回4。
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* pattern 返回sour中tar的个数,tar中允许使用通配符'?',代表任意一个字符
* 例如tar为"?s", sour为"This is a thesis." 返回4
*/
int pattern(const char *tar, const char *sour)
{
assert(tar != NULL && sour != NULL);
int count = 0;
int i = 0;
int j = 0;
const int tarlen = strlen(tar);
const int sourlen = strlen(sour);
while (j < sourlen)
{
if (tar[i] == '?' || tar[i] == sour[j])
{
++i;
++j;
if (tarlen == i)
{
j = j - i + 1;
i = 0;
++count;
}
}
else
{
j = j - i + 1;
i = 0;
}
}
return count;
}
/*
* firstpattern 返回sour中tar的出现的位置,若sour中没有tar,返回-1
* tar中允许使用通配符'?' ,代表任意一个字符。
* 例如tar为"?s", sour为"This is a thesis." 返回2。
* 例如tar为"?c", sour为"This is a thesis." 返回-1。
*/
int firstpattern(const char *tar, const char *sour)
{
assert(tar != NULL && sour != NULL);
int index = - 1;
int i = 0;
int j = 0;
const int tarlen = strlen(tar);
const int sourlen = strlen(sour);
while (i < tarlen && j < sourlen)
{
if (tar[i] == '?' || tar[i] == sour[j])
{
++i;
++j;
}
else
{
j = j - i + 1;
i = 0;
}
}
if (tarlen == i)
{
index = j - i;
}
return index;
}
void Test(void)
{
int count = 0;
char source[] = "This is a thesis.";
char target[] = "cs";
int result = pattern(target, source);
int index = firstpattern(target, source);
printf("There %s %d /"%s/" in /"%s/"/n", /
(result <= 1) ? "is" : "are", result, target, source);
if ( - 1 == index)
{
printf("There is no /"%s/" in /"%s/"/n", /
target, source);
}
else
{
printf("The first /"%s/" is at %d in /"%s/"/n", /
target, index, source);
}
}
int main()
{
Test();
return 0;
}
以上算法只支持'?'通配符,不支持'*'通配符。而且也没有使用KMP匹配算,所以效率不高。
本文介绍了一种在源字符串中查找包含'?'通配符的目标子字符串的方法,并提供了两个函数:pattern用于计算目标子字符串在源字符串中出现的次数;firstpattern用于找到目标子字符串首次出现的位置。
671

被折叠的 条评论
为什么被折叠?



