gpt4 book ai didi

比较c中的2个字符串递归

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

我写了一个函数,获取2个字符串并递归比较它,有一些规则:如果有双字母或小字母而不是大写/相反,则返回 1 ,否则0 。它应该返回 1如果s1是大写字母还是小写字母,s是相反的但不知道如何,我尝试了 *s-32/*s+32但我无法确定使用哪个或何时使用。

这是函数代码:

int CompareS(char *s, char *s1)
{

if (*s == NULL && *s1==NULL)
return 1;

if (strncmp(s, s1, 1) != 0 )
{
if (strncmp(s, s - 1, 1) == 0)
return CompareS(s + 1, s1);
else
return 0;
}
else
return CompareS(s + 1, s1 + 1);
}

最佳答案

我真的很喜欢这个问题,所以我决定尝试。这是带注释的代码。所以我就这样进行了

return 0 :两个字符串相等

return -1 :两个字符串相等

return -2 :一个或两个指针都是 NULL 指针

#include <string.h> //to use the strcmp() function
#include <stdio.h>
#include <ctype.h> // tolower() function in order to ignore the
// lower and upper cases

int CompareS(char *s, char *s1)
{
// if one of the pointer is a NULL pointer return directly -2
// in order to stop the process
if(s==NULL || s1==NULL)
return -2;
// if the function strcmp return 0 this means that the rest of
// the two strings are identical
if(strcmp(s,s1)==0)
return 0;

// we need to see the next character to know which pointer
// will be incremented in the next recursive call
if(tolower(s[0])==tolower(s1[0]) && tolower(s[0])==tolower((s1+1)[0]))
CompareS(s, ++s1);
else if(tolower(s[0])==tolower(s1[0]) && tolower(s1[0])==tolower((s+1)[0]))
CompareS(++s, s1);
else if(tolower(s[0])==tolower(s1[0]))
CompareS(++s, ++s1);
else
return -1;
}

对该程序进行字符串 helloHeLLlloOOO 的小型测试

int main()
{
char str[100]="hello",s[100]="HeLLlloOOO";
printf("the result of comparison is %d\n",CompareS(s, str));

return 0;
}

给出

the result of comparison is 0

希望有帮助!

关于比较c中的2个字符串递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28098765/

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