c语言字符串匹配问题,KMP字符串匹配算法C语言实现

#i nclude

#i nclude

#i nclude

#i nclude

//获得prefix数组

int* GetPrefixValue(char* strPattern, int iPatternLen)

{

int i, j; /* i runs through the string, j counts the hits*/

int* prefix = (int*)malloc(iPatternLen*sizeof(int));

i = 1; j = 0;

prefix[0] = 0;

while(i

{

if(strPattern[i] == strPattern[j])

{

prefix[i] = ++j;

}

else

{

j = 0;

prefix[i] = j;

}

i++;

}

return prefix;

}

//返回target串在pattern串中第一次匹配的index

int KMPStringMatch(char* strPattern, int iPatternLen, char* strTarget, int iTargetLen, int* prefix)

{

int i = 0;

int j = 0;

while(i

{

if(j==0 || strPattern[i]==strTarget[j])

{

i++;  j++;

}

else

{

j = prefix[j];

}

}

free(prefix);

if(j==iTargetLen)

{

return i-j;

}

else

{

return -1;

}

}

int KMP(char* strPattern, char* strTarget)

{

int* prefix = GetPrefixValue(strPattern, strlen(strPattern));

int index = KMPStringMatch(strPattern, strlen(strPattern), strTarget, strlen(strTarget), prefix);

return index;

}

//在文本文件中查找target串出现的行数

int SearchInTxtFile(char* fileName, char* strTarget)

{

FILE* hFile = fopen(fileName, "r");

char str[1024];

int count = 0;

while(fgets(str, 1024, hFile))

{

if(KMP(str, strTarget)!=-1)

{

count++;

}

}

fclose(hFile);

hFile=NULL;

return count;

}

int main()

{

char ch;

char str1[] = "abcabcabctasksb,abTo";

char str2[] = "abc";

double t=clock();

printf("%d\n", KMP(str1,str2));

printf("耗时:%f毫秒!\n", (clock()-t));

t=clock();

printf("find %d \n", SearchInTxtFile("c:\\txt.txt", "NULL"));

printf("耗时:%f毫秒!\n", (clock()-t));

scanf("%c", &ch);

return 0;

}

posted on 2006-07-05 23:48 Bourne 阅读(4480) 评论(4)  编辑 收藏 引用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值