gpt4 book ai didi

c - C语言中计算两个字符串匹配次数的函数

转载 作者:行者123 更新时间:2023-11-30 15:11:51 25 4
gpt4 key购买 nike

我试图找出c中两个字符串匹配的次数,如果我们有两个或更多星星,多个字符串组合可能是合适的。例如 "abcdb""*b*" 匹配两次。我当前的代码可以工作,但它返回四个。我不知道我在这里缺少什么。

#include <stdio.h>

int nmatch(char *s1, char *s2) {
if (*s1 != '\0' && *s2 != '\0' && *s2 == '*' && (*s2 + 1) != *s1) {
return nmatch(s1 + 1, s2) + 1;
}
if (*s1 == *s2) {
return nmatch(s1 + 1, s2 + 1);
}
if (*s1 == *s2 && *s1 == '\0' && *s2 == '\0') {
return 0;
}
return (1);
}

int main() {
char ap[] = "abcd";
char ab[] = "*b*";
printf("%d", nmatch(ap, ab));
return 0;
}

最佳答案

您的代码只是不计算 s1 与模式 s2 匹配的不同方式的数量。对于相同的字符串,它甚至不会返回 1。

第一个比较 (*s2 + 1) != *s1 不正确,您的意思可能是 *(s2 + 1) != *s1 相当于 s2[1] != *s1,但此修复不足以纠正算法。

这是一个简单的实现,它可以:

int nmatch(const char *s1, const char *s2) {
int count;
while (*s2 != '\0' && *s2 != '*' && *s1 == *s2) {
s1++;
s2++;
}
if (*s2 == '\0')
return *s1 == '\0';
if (*s2 != '*')
return 0;
while (*s2 == '*') /* skip all stars */
s2++;
if (*s2 == '\0')
return 1;
for (count = 0;; s1++) {
count += nmatch(s1, s2);
if (*s1 == '\0')
break;
}
return count;
}

关于c - C语言中计算两个字符串匹配次数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com