我编写了一个获取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);
}
答案 0 :(得分:0)
我真的很喜欢这个问题所以我决定尝试尝试。这是带注释的代码。所以我继续这样做
return 0
:两个字符串相等
return -1
:两个字符串 NOT 相等
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;
}
针对字符串hello
和HeLLlloOOO
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
希望它有所帮助!