c++编写一个void Reverse(string &s)函数,还要用递归,使字符串倒序。

u014530518 2014-04-03 04:32:02
求助,谁能写个简单的给我
...全文
724 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lm_whales 2014-04-09
  • 打赏
  • 举报
回复
void Reverse(string &s){ Reverse(s,0,s.size()-1); }
lm_whales 2014-04-04
  • 打赏
  • 举报
回复
#include<string>
#include<iostream>
using namespace std;

void Reverse(string &s,int i,int j){
         if(i>=j)return;
         char c = s[i]; s[i] = s[j]; s[j]=c;
         Reverse(++i,--j);
}
void Reverse(string &s){     Reverse(0,s.size()-1); }

int main()
{
        string s("abcdefg");
        cout<<"Before reverse: s = "<<s<<endl;
        Reverse(s);
        cout<<"After reverse: s = "<<s<<endl; 
}
lm_whales 2014-04-04
  • 打赏
  • 举报
回复
void Reverse(string &s,int i,int j){ if(i>=j)return; char c = s[i]; s[i] = s[j]; s[j]=c; Reverse(++i,--j); } void Reverse(string &s){ Reverse(0,s.size()-1); } int main() { string s("abcdefg"); cout<<"Before reverse: s = "<<s<<endl; Reverse(s); cout<<"After reverse: s = "<<s<<endl; } PS : 这种事情为何要使用递归???
测试NULL 2014-04-04
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>

using namespace std;

void Reverse(string &s)
{
    size_t len = s.length();
    static int index = 0;

    if (index <= (len/2))
    {
        char temp = s[index];
        s[index] = s[len-index-1];
        s[len-index-1] = temp;
        
        ++index;
        Reverse(s);
    }
}

int main(int argc, const char * argv[])
{
    string s = "abcdefg";
    Reverse(s);
    
    cout << s << endl;
    
    return 0;
}
测试NULL 2014-04-03
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>

using namespace std;

void Reverse(string &s)
{
    static string copy_str = string(s.length(), '\0');
    static int index;

    if (index == s.length())
    {
        s = string(copy_str);
        return;
    }
    
    copy_str[index] = s[s.length()-index-1];
    index++;
    
    Reverse(s);
}

int main(int argc, const char * argv[])
{
    string s = "abcdefg";
    Reverse(s);
    
    cout << s << endl;
    
    return 0;
}
测试NULL 2014-04-03
  • 打赏
  • 举报
回复

#include <string>
#include <iostream>

using namespace std;

void Reverse(string &s, int index)
{
    static string copy_str = string(s.length(), '\0');

    if (index == s.length())
    {
        cout << copy_str << endl;
        return;
    }
    
    copy_str[index] = s[s.length()-index-1];
    
    Reverse(s, index+1);
}
int main(void)
{
    string s = "abc";
    Reverse(s, 0);
    
    return 0;
}

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧