简体   繁体   English

通过C ++中的递归进行字符串反转

[英]string reversal via recursion in c++

i have tried my code after looking for some solutions online. 我在网上寻找一些解决方案后尝试了我的代码。 There was one algorithm regarding string reversal via recursion and i tried my best to make my code according to that algorithm. 有一种关于通过递归进行字符串反转的算法,我尽力根据该算法来编写代码。 unfortunately, my code only swaps the first and the last characters in the given string but not the characters second with second last and so on. 不幸的是,我的代码仅交换给定字符串中的第一个和最后一个字符,而不交换第二个字符与第二个倒数,依此类推。 any help would be appreciated here's my code: 任何帮助将不胜感激,这是我的代码:

string reverse(string s,int length,int start=0){

    if (start>=length){
        return s;
    }
    else{
        char temp=s[length];
        s[length]=s[start];
        s[start]=temp;
        reverse(s,--length,++start);
    }return s;
}

int main(void) {

    string a;cout<<"enter a string:";getline(cin,a);
    cout<<reverse(a,a.length()-1,0);
}

Instead of returning s , which is a copy of the original string with the first and last characters switched, you need to return the next call to reverse() : 您无需返回s (它是原始字符串的副本,其中第一个和最后一个字符已切换),而不是返回下一个对reverse()调用:

else{
    //...
    return reverse( s, --length, ++start );
}

You need to pass the string by reference, not by value in the reverse function: 您需要通过引用传递字符串,而不是通过reverse函数传递值:

string reverse(string& s,int length,int start=0){

Live Example: http://ideone.com/pJ3G9l 实时示例: http//ideone.com/pJ3G9l

The reason why a reference works is that you are reversing the current string, not a temporary string. 引用起作用的原因是您要反转当前字符串,而不是临时字符串。

As the comment suggested, if the desired effect is to not alter the original string, then a helper function that does the recursion would work. 正如评论所建议的那样,如果所需的效果是不更改原始字符串,则执行递归的辅助函数将起作用。

string reverse_helper(string& s,int length,int start)
{
    if (start>=length)
        return s;
    else
    {
        char temp=s[length];
        s[length]=s[start];
        s[start]=temp;
        reverse_helper(s,--length,++start);
    }
    return s;
}

string reverse(string str, int length, int start=0)
{
    return reverse_helper(str, length, start);
}

Live example of helper function: http://ideone.com/RzY1Bu 辅助功能的实时示例: http : //ideone.com/RzY1Bu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM