gpt4 book ai didi

c++ - 匹配数组中的确切位置

转载 作者:行者123 更新时间:2023-11-28 02:16:50 26 4
gpt4 key购买 nike

我能够创建一个函数来搜索并返回单词中的多个匹配字符,但现在我无法创建另一个函数来搜索两个单词是否完全匹配到位置并返回数字的比赛。约束是 c 字符串。所以如果一个词很小,我输入了 tine,它应该返回 3。

我在下面附加的功能只是我能够弄清楚的功能

int countMatches(const char s1[], const char s2[])
{
char s1copy[MAXWORDLEN+1];
strcpy(s1copy, s1);

int nMatches = 0;

// For every character in s2

for (int k2 = 0; s2[k2] != '\0'; k2++)
{
// For every character in the copy of s1

for (int k1 = 0; s1copy[k1] != '\0'; k1++)
{
// If they match, blot it out of the copy of s1
// so it won't be matched again

if (s1copy[k1] == s2[k2])
{
nMatches++;
s1copy[k1] = '#';
break;
}
}
}
return nMatches;
}

最佳答案

int countMatches(const char s1[], const char s2[]) {
int i = 0;
while (s1[i] != '\0' && s2[i] != '\0' && s1[i] == s2[i])
i++;
return i;
}

关于c++ - 匹配数组中的确切位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793085/

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