c++ - 两个字符串的递归比较

标签 c++ recursion c-strings

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 == '\0')
    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 == '\0' && *string2 == '\0') {
        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

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

相关文章:

c++ - c++随机交换数组中的两个元素

c++ - XMLDOMNodePtr::get_text() 是否需要显式释放?

javascript - 使用 Node JS 递归获取 DynamoDB 查询中的所有项目

java - 递归函数打印出一些我认为不应该打印的东西

java - Java中是否可以使用递归无限地运行程序?

c++ - 如果我在 GetBuffer 之后不调用 ReleaseBuffer 怎么办?

c++ - 如何创建 C 字符串数组?

c++ - 无法初始化类成员?

c++ - 基本 OpenCV Hello World 的错误

c - 函数内部使用malloc形成字符串时的段错误(11)