【发布时间】:2014-06-29 04:22:23
【问题描述】:
我想获得 Boyer-Moore-Horspool 实现来搜索文本文件中的某些字符串。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int bmhSearch(char *needle) {
FILE *fp;
int find_result = 0;
char temp[512];
size_t nlen = strlen(needle);
size_t scan = 0;
size_t bad_char_skip[UCHAR_MAX + 1];
size_t last;
if((fopen_s(&fp, "book.txt", "r")) != NULL) {
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
size_t hlen = strlen(temp);
/* pre */
for (scan = 0; scan <= UCHAR_MAX; scan = scan + 1)
bad_char_skip[scan] = nlen;
last = nlen - 1;
for (scan = 0; scan < last; scan = scan + 1)
bad_char_skip[needle[scan]] = last - scan;
while (hlen >= nlen){
/* scan from the end of the needle */
char *ptemp = temp;
for (scan = last; ptemp[scan] == needle[scan]; scan = scan - 1){
if (scan == 0){
find_result++;
}
}
hlen -= bad_char_skip[ptemp[last]];
ptemp += bad_char_skip[ptemp[last]];
printf("%d\t%d\n", hlen, nlen);
}
}
if(fp) {
fclose(fp);
}
return find_result;
}
int main(void){
char needle[30] = {"some text like this"};
printf("Matches found: %d\n", bmhSearch(needle);
}
我相信,我做错了很多事情,但我真的找不到并修复它。
我唯一得到的是在某个阶段程序不符合条件while(hlen >= nlen)。
【问题讨论】:
-
你的问题是什么?如果您没有任何具体内容,只想进行代码审查,请转到 CodeReview SE。这里的人喜欢解决编程问题。人们喜欢说别人的代码有什么问题。
-
第 1 步:将字符串搜索与文件读取等内容分开。第 2 步:启动调试器。
-
@luk32:Code Review.SE 仅适用于工作的代码。
-
@JerryCoffin OP 相信他的代码是错误的,并且没有命名一个不起作用的东西。所以也许他只需要审查。
-
@luk32 如果我知道问题出在哪里,我想我不会创建这篇文章。 :) 顺便说一句,我使用调试器尝试找出问题所在。所以我认为 'hlen' 变量溢出了,但我不确定。
标签: c string search boyer-moore