递归比较字符串的函数 - C ++

时间:2016-01-22 04:24:19

标签: c++ string recursion

我必须编写一个名为relation的函数来比较两个字符串。问题表明我仅限于使用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);
    }
}

当我运行它时,这些是我得到的错误。随着改变一些东西,我可以让它运行,但我认为它进入一个无限循环,因为它需要一段时间运行,只是崩溃。

enter image description here 如果我能得到一些帮助,我会非常感激。

2 个答案:

答案 0 :(得分:2)

看起来你误解了一些数据类型,然后尝试了一些黑客来阻止编译器错误。这是第一个。

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 );

或者你可以使用rvalues将它拼成一行:

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

这应该足以让你前进。

答案 1 :(得分:1)

没有理由采取一切的地址。您应该使用s1[0],而不是&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);
    }
}