C 如何有效地在另一个阵列中查找子阵列的所有匹配项?
例如,这就是我现在实施的方式:C 如何有效地在另一个阵列中查找子阵列的所有匹配项?,c,arrays,search,optimization,C,Arrays,Search,Optimization,例如,这就是我现在实施的方式: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> size_t *find_matches(char *needle, size_t needleSize, char *haystack, size_t haystackSize, size_t *size) { size_t max_matches = 256; size_t *matche
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
size_t *find_matches(char *needle, size_t needleSize, char *haystack, size_t haystackSize, size_t *size) {
size_t max_matches = 256;
size_t *matches = malloc(sizeof(size_t) * max_matches);
int matchCount = 0;
for(int i = 0; i + needleSize <= haystackSize; i++) {
bool matched = true;
for(int j = 0; j < needleSize; j++) {
if(haystack[i + j] != needle[j]) {
matched = false;
break;
}
}
if(matched) {
matches[matchCount] = i;
matchCount++;
if(matchCount == max_matches) {
break;
}
}
}
*size = matchCount;
return matches;
}
int main() {
char needle[] = {0xed, 0x57, 0x35, 0xe7, 0x00};
char haystack[] = {0xed, 0x57, 0x35, 0xe7, 0x00, ..., 0xed, 0x57, 0x35, 0xe7, 0x00, ...};
size_t size;
size_t *matches = find_matches(needle, sizeof(needle), haystack, sizeof(haystack), &size);
for(size_t i = 0; i < size; i++) {
printf("Match %zi: %zi\n", i, matches[i]);
}
return 0;
}
#包括
#包括
#包括
大小*查找匹配项(字符*针,大小*针,字符*干草堆,大小*干草堆大小,大小*大小){
大小\u t最大\u匹配=256;
大小匹配=malloc(大小匹配)*最大匹配);
int matchCount=0;
对于(int i=0;i+needleSize请参见和其他(,)。?这称为字符串搜索。有许多算法可以提高搜索效率,尽管它们可能有些复杂。@VaughnCato为什么要创建注释而不是答案?@AlexeyFrunze抄送给您:-)@junix Aye,Aye,cap!:)我在C中找到了Rabin Karp的这个实现:但是它失败了:pattern=“\xff”;text=“\x00\xff”
。你知道如何解决这个问题吗?想想。字符串以NUL结尾,什么是strlen(“\x00\xff”)
?@Alexey_Frunze抱歉,我忘了说我用函数的参数替换了N
和M
的strlen
。它仍然找不到它。就像这样:调试代码。如果你理解算法并知道如何使用调试器,你应该能够这样做。@Alexey_Frunze这是因为检查了negat
的无效值,因为char
不是无符号的,对吗?