【问题标题】:compare 2 string recursive in c在c中比较2个字符串递归
【发布时间】:2015-03-21 20:01:49
【问题描述】:

我写了一个函数,它获取 2 个字符串并递归比较它,有一些规则:如果有双字母或小而不是大写/相反,则返回 1,否则返回 0。如果s1 是大写字母或小写字母,它应该返回1,而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);
}

【问题讨论】:

标签: c string algorithm recursion


【解决方案1】:

我真的很喜欢这个问题,所以我决定试试。这是带有 cmets 的代码。于是我就这样继续下去了

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

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2015-10-25
    • 2019-11-10
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多