c++ - 在 C++ 中使用递归函数反转字符串

标签 c++ string function recursion

为了探索我对递归的理解,我尝试使用递归函数来反转字符串。这看起来应该比现在对我来说更简单。谁能告诉我我做错了什么。当我执行下面的代码时,它会产生一个空行。我在这里四处寻找类似的主题,但每件事都是用其他语言写的……令我惊讶的是。

#include <iostream>
#include <string>

using namespace std;


/**
    Recursivly reverses a string
    @param return last_char, the last character currently in the string
    @param go, the recursive function to return the character and continue     within the function
    **/
char string_reverse(string word)
{

    if (word.length()-1 > 0)
    {
    char last_char = word[word.length()-1];
    word.erase(word.length()-1);
    char go = string_reverse(word);
    return go;

    }

else 
    return false;

}


int main()
{
cout << "Enter a string: ";
string input;
getline(cin, input);
string last;
last = last + string_reverse(input);
cout << last << endl;

/*char fig = string_reverse(input, fig);
cout << fig << endl;
*/

system("pause");
return 0;
}

最佳答案

string_reverse中,您应该返回最后一个字符 + string_reverse(word) + 第一个字符

在您的 else 中,返回一个空字符串,这样您就不会遇到输入错误。

调用该函数时,不要对word做任何其他操作,只需调用string_reverse(word)

综合起来:

#include <iostream>
#include <string>

using namespace std;


/**
    Recursivly reverses a string
    @param return last_char, the last character currently in the string
    @param go, the recursive function to return the character and continue
    within the function
    **/
string string_reverse(string word)
{

    if (word.length()-1 > 0)
    {
    string first_char = word.substr(0,1);
    string last_char = word.substr(word.size()-1,1);
    string middle = word.substr(1, word.size()-2);
    return last_char + string_reverse(middle) + first_char;

    }

else 
    return "";

}


int main()
{
cout << "Enter a string: ";
string input;
getline(cin, input);
cout << string_reverse(input); << endl;

system("pause");
return 0;
}

然而,对于奇数字母计数,这将失败。 “c”将输出“cc”。我会把它留给你。

关于c++ - 在 C++ 中使用递归函数反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15704660/

相关文章:

c++ - std::cout 和 printf 正在从 C++ 中删除字符

javascript - 在 JavaScript 中将整个字符串转换为整数

c++ - 继承运算符 +()

c++ - 为什么这些代码仍然使用左值函数?

c - 在 ANSI C 中使用指针替换字符

r - 如何使用 for 循环将函数应用于数据框中列中的特定值

function - 如何在 PowerShell 中创建和使用自定义函数属性?

algorithm - 查找数组中的偶数

c++ - C++ 中的 char* 问题

php - 从文本框搜索关键字到mysql