两个字符串的递归比较

Recursive comparison of two strings

本文关键字:递归 比较 字符串 两个      更新时间:2023-10-16

函数int compare(...)检查2个字符串是否相等,忽略大小写和任何非字母字符,例如"a?...!b"等同于"ab"。如果相等,则返回 1,否则返回 0。但是,我的代码中有一个错误!

int compare(const char* string1, const char* string2)
{
  if(string1 == NULL || string2 == NULL)
    return 0;
   std::cout << *string1 << " | " << *string2 << std::endl;
   if((!isalpha(*string1) && *string1 != ' ') && (!isalpha(*string2) && *string2 != ' '))
    {
      compare(++string1,++string2);
    }
   else if(!isalpha(*string1) && *string1 != ' ')
    {
      compare(++string1,string2);
    }
   else if(!isalpha(*string2) && *string2 != ' ')
    {
     compare(string1, ++string2);
    }
  if(tolower(*string1) != tolower(*string2))
    return 0;
  if(*string1 == '')
    return 1;
  if(*string1 == *string2)
    compare(++string1, ++string2);
}

例如,如果我尝试运行此代码:

compare("a !!!b", "a b");

输出真的让我感到困惑:

a | b
  | 
! | 
! | 
! | 
b | b
^@| ^@
  | a
^@| ^@
  | a

它返回 0(不等于)。一旦到达 b | b,它就不会停止运行,为什么?

除了需要return语句之外,你的逻辑还有一个缺陷。您需要检查两个字符串是否为空,因此在函数的前面是否相等:

int compare(const char* string1, const char* string2)
{
    if(string1 == NULL || string2 == NULL)
        return 0;
    // This needs to go here
    if(*string1 == '' && *string2 == '') {
        return 1;
    }
    std::cout << *string1 << " | " << *string2 << std::endl;
    if((!isalpha(*string1) && *string1 != ' ') && (!isalpha(*string2) && *string2 != ' '))
    {
        return compare(++string1,++string2);
    }
    else if(!isalpha(*string1) && *string1 != ' ')
    {
        return compare(++string1,string2);
    }
    else if(!isalpha(*string2) && *string2 != ' ')
    {
        return compare(string1, ++string2);
    }
    if(tolower(*string1) != tolower(*string2))
        return 0;
    if(*string1 == *string2)
        return compare(++string1, ++string2);
}

你可以在这里查看:https://ideone.com/Si78Nz