我正在尝试比较2个字符串之间的相似字符数,并遇到了strpbrk()函数。但是我找不到任何将搜索字符串拆分为字符数组的方法。
char search[] = "chzi";
char arr[2][20] = {"cheang", "wai"};
float lengthSearch = strlen(search);
float count = 0;
for(int i = 0; i < 2; i++){
int lengthArr = strlen(arr[i]);
for(int j = 0; j < lengthSearch; j++){
if(strpbrk(&search[j], arr[i])){
printf("%c is the similarity between %s and %s\n", *strpbrk(&search[j], arr[i]), &search[j], arr[i]);
count++;
printf("count is now %.1f\n", count);
}
}
float probability = ((count/lengthSearch) * (count/lengthArr)) * 100;
printf("%s has a probability of %.2f\n\n", arr[i], probability);
count = 0;
}
问题在这里
i is the similarity between chzi and wai
count is now 1.0
i is the similarity between hzi and wai
count is now 2.0
i is the similarity between zi and wai
count is now 3.0
i is the similarity between i and wai
count is now 4.0
我只想比较c和wai,而不是chzi
答案 0 :(得分:2)
我想检查
search
和arr[i]
然后您可以使用strpbrk
,但是与您尝试的方式有些相反。 man 3 strpbrk
,声明为
char *strpbrk(const char *s, const char *accept); locates the first occurrence in the string s of any of the bytes in the string accept.
因此,您要做的就是简单地与strpbrk
循环并找出search
共有多少个arr[i]
字符。使用指针可以简化操作,例如
#include <stdio.h>
#include <string.h>
int main (void) {
char search[] = "chzi",
arr[][20] = {"cheang", "wai"};
size_t n = sizeof arr / sizeof *arr;
for (size_t i = 0; i < n; i++) {
size_t count = 0;
char *p = arr[i];
while ((p = strpbrk (p, search)))
count++, p++;
printf ("%s contains %zu occurrence of characters in %s.\n",
arr[i], count, search);
}
}
请注意,您只需使用指向arr[i]
的指针,然后使用strpbrk
来定位search
中arr[i]
中出现的第一个字符。然后,您将指针增加到arr[i]
中的下一个字符(使用p++;
),并再次进行操作,直到strpbrk
返回NULL
为止,指示{{1} }与arr[i]
中的任何字符匹配,上面的代码就是这样做的,例如
search
如果您想避免使用逗号运算符,它将是:
char *p = arr[i];
while ((p = strpbrk (p, search)))
count++, p++;
使用/输出示例
运行字符串会导致:
char *p = arr[i];
while ((p = strpbrk (p, search))) {
count++;
p++;
}
仔细研究一下,让我知道您是否打算这样做。您将需要添加概率代码,但这留给您。