C++ 反向字符串递归 [英] C++ reverse string recursion

查看:57
本文介绍了C++ 反向字符串递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试递归反转字符串.如果str1 == "hello",我想让str1变成"olleh".在我的递归函数中,我试图将第一个字符复制到一个临时变量中,递归地传递字符串并将临时变量的内容附加到返回字符串的末尾.到目前为止,这是我的代码,

I am trying to recursively reverse a string. If str1 == "hello", I want str1 to become "olleh". In my recursive function, I am trying to copy the first character into a temporary variable, pass the string recursively and append the contents of the temporary variable to the end of the returned string. So far, this is my code,

# include <iostream>
# include <string.h>
using namespace std;

string string_reverse(string) ;

int main ()
{
    string str1 = "hello";

    cout << string_reverse(str1) << endl;

    return 0;
}

string string_reverse(string str1)
{
    if (str1.length() == 1)
    { return str1;}
    else
        string temp;
        temp.assign(str1, 0, 1);
        str1.erase(0, 1);
        string_reverse(str1);
        return str1.append(temp);
}

但是,我收到一条错误消息,指出 temp 未在范围内声明.

However, I am getting an error saying temp was not declared within the scope.

推荐答案

你缺少一个 { 和一个 } -- 没有它们,你的 else 子句就只是那一行 string temp;.

You're missing a { and a } -- without them, your else clause is just that one line string temp;.

使用自动重排代码的编辑器可以帮助您了解此类情况.

Using an editor that reflows your code automatically can help you see such things.

这篇关于C++ 反向字符串递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆