让我们看看我会怎么做:
您将需要一个函数,给定一个char 数组,将其拆分为一个单词数组(并将它们放在C 字符串中,请以NUL 终止:-))。我会把这个数组的长度和数组放在一个结构中
struct WordCollection
{
size_t NumWords;
char **Words;
}
现在...如何实现这个功能?
假设我们“作弊”了一点,并确定我们的数组 A 和 B 是 NUL 终止的(或者如果它们是像 B 一样终止的 .,那么您将 . 替换为 NUL)。现在,这是 C,您应该首先计算字符串中的空格数,分配一个足够大的 char* (WordCollection::Words) 数组以包含 n + 1 char*(并将此 n + 1 放入 @987654336 @) 并使用strtok“标记”字符串并将单词放入您创建的数组中。
那么您应该(可以)使用此函数将 A 和 B 数组拆分为单词。您将获得两个WordCollection,A1 和 B1。
为了更快,我会qsort B1。
然后,对于 A1 中的每个单词,您在 B1 中 bsearch 它(这不是一个坏词……这意味着二进制搜索,它是在有序数组中搜索某些内容的快速方法)
完成:-)
我要补充一点,如果这是您第一次使用bsearch 和qsort,最好看看您可以找到的示例。它们的语法可能很“棘手”。
现在...我知道你不会看代码 :-) 所以我会把它放在这里
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordCollection
{
size_t NumWords;
char **Words;
};
void splitWord(char *str, struct WordCollection *wc)
{
char *c;
char **currentWord;
c = str;
wc->NumWords = 1;
while (*c != '.')
{
if (*c == ' ')
{
wc->NumWords++;
}
c++;
}
*c = '\0';
wc->Words = (char**)malloc(wc->NumWords * sizeof(char*));
c = strtok(str, " ");
currentWord = wc->Words;
while (c)
{
*currentWord = c;
currentWord++;
c = strtok(NULL, " ");
}
}
int myComp(const void *p1, const void *p2)
{
return strcmp(*(const char**)p1, *(const char**)p2);
}
int main(void)
{
char a[] = { 'w', 'o', 'r', 'n', 'g', ' ', 'w', 'o', 'r', 'd', '.' };
char b[] = { 'c', 'o', 'r', 'r', 'e', 'c', 't', ' ', 'w', 'o', 'r', 'd', '.' };
struct WordCollection a1, b1;
struct WordCollection *pSmaller, *pBigger;
size_t i;
splitWord(a, &a1);
splitWord(b, &b1);
if (a1.NumWords <= b1.NumWords)
{
pSmaller = &a1;
pBigger = &b1;
}
else
{
pSmaller = &b1;
pBigger = &a1;
}
qsort(pBigger->Words, pBigger->NumWords, sizeof(char*), myComp);
for (i = 0; i < pSmaller->NumWords; i++)
{
void *res = bsearch(&pSmaller->Words[i], pBigger->Words, pBigger->NumWords, sizeof(char*), myComp);
if (res)
{
printf("Found: %s", pSmaller->Words[i]);
}
}
free(a1.Words);
free(b1.Words);
return 0;
}
然后在ideone