【问题标题】:Function to compare strings recursively - C++递归比较字符串的函数 - C++
【发布时间】:2016-04-28 14:20:16
【问题描述】:

我必须编写一个名为关系的函数来比较两个字符串。问题表明我仅限于使用 C++ 关系运算符 比较单个字符。

这是我到目前为止的位置,但我只是得到错误。

char relation (const std::string& s1, const std::string& s2) {
    if(&s1[0] == "" || &s2[0] == ""){
        return '=';
    }
    else if(&s1[0] < &s2[0]){
        return '<';
    }
    else if(&s1[0] > &s2[0]){
        return '>';
    }
    else{
        std::string new_s1 = &s1.substr(1);
        std::string new_s2 = &s2.substr(1);
        return relation(s1,s2);
    }
}

当我运行它时,这些是我得到的错误。通过改变周围的一些东西,我可以让它运行,但我假设它进入了一个无限循环,因为它需要一段时间运行并且会崩溃。

如果我能得到一些帮助,我将不胜感激。

【问题讨论】:

  • 当您在调试器中单步执行此代码时发生了什么?
  • 您为什么使用&amp;s1[0] 而不仅仅是s1[0]?比较的是地址,而不是字符。
  • 递归调用应该使用new_s1new_s2
  • (1) 请更好地描述您的问题,而不是“只是得到错误”和“只是崩溃”。 (2)if(&amp;s1[0] == "" || &amp;s2[0] == ""),即使你摆脱了&amp;s,也是错误的。
  • 我相信我已经解决了我用 if(s1[0] == '\0' && s2[0] == '\0') 并且它现在起作用了

标签: c++ string recursion


【解决方案1】:

您似乎误解了某些数据类型,然后尝试了一些技巧来阻止编译器错误。这是第一个。

if(&s1[0] == "" || &s2[0] == "")  // wrong

您正在尝试测试字符串是否为空,但您获取的是一个字符,然后引用它以获取一个 char* 可以与字符串文字 "" 进行比较,除了结果总是会是假的。

如果要检查空字符串,请使用std::string::empty

if( s1.empty() || s2.empty() )

请注意,逻辑不正确。字符串只有在两个都为空时才相等,如果只有一个为空则不相等。

同样,这里:

else if( &s1[0] < &s2[0] )  // wrong

您正在进行指针比较,而不是字符比较。这应该是:

else if( s1[0] < s2[0] )

最后,一旦你修复了编译器错误,你会遇到堆栈溢出,因为你在错误的字符串上进行递归,并且你再次获取了一个引用:

std::string new_s1 = &s1.substr(1);   // wrong
std::string new_s2 = &s2.substr(1);   // wrong
return relation(s1,s2);               // passing original instead of substring

相反,这应该是:

std::string new_s1 = s1.substr(1);
std::string new_s2 = s2.substr(1);
return relation( new_s1, new_s2 );

或者您可以使用右值将其插入一行:

return relation( s1.substr(1), s2.substr(1) );

这应该足以让你继续前进。

【讨论】:

    【解决方案2】:

    没有理由获取所有内容的地址。你应该使用s1[0],而不是&amp;s1[0]

    执行递归调用时,需要使用new_s1new_s2作为参数,而不是s1s2

    您测试字符串是否为空的方法是错误的。 s1[0]char,而不是字符串,因此您不应将其与 "" 进行比较。如果 其中一个 字符串为空,您还会报告 =;只有当两个字符串都为空时,它们才相等。

    char relation (const std::string& s1, const std::string& s2) {
        if(s1[0] == '\0' && s2[0] == '\0'){
            return '=';
        }
        else if(s1[0] < s2[0]){
            return '<';
        }
        else if(s1[0] > s2[0]){
            return '>';
        }
        else{
            std::string new_s1 = s1.substr(1);
            std::string new_s2 = s2.substr(1);
            return relation(new_s1, new_s2);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-25
      • 2019-07-24
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多