编写一个递归函数来反转输入字符串 [英] Write a recursive function that reverses the input string

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

问题描述

我一直在阅读 C++ For Everyone 一书,其中一个练习说要编写一个函数 string reverse(string str),其中返回值是 str 的反函数代码>.

I've been reading the book C++ For Everyone and one of the exercises said to write a function string reverse(string str) where the return value is the reverse of str.

有人可以写一些基本的代码并向我解释一下吗?我从昨天开始就一直盯着这个问题,无法弄清楚.我得到的最远的是让函数返回 str 的第一个字母(我仍然不知道它是怎么发生的)

Can somebody write some basic code and explain it to me? I've been staring at this question since yesterday and can't figure it out. The furthest I've gotten is having the function return the first letter of str (Which I still don't know how it happened)

这是我得到的(发布这个问题一个小时后):

This is as far as I got (An hour after posting this question):

string reverse(string str)
{
    string word = "";

    if (str.length() <= 1)
    {
        return str;
    }
    else
    {
        string str_copy = str;
        int n = str_copy.length() - 1;
        string last_letter = str_copy.substr(n, 1);

        str_copy = str_copy.substr(0, n);
        word += reverse(str_copy);
        return str_copy;
    }
    return word;
}

如果我输入Wolf",它会返回 Wol.有人帮我在这里如果我 return word 而不是 return str_copy 那么我得到一个 w如果我 return last_letter 然后我得到一个 l

If I enter "Wolf", it returns Wol. Somebody help me out here If I return word instead of return str_copy then I get a w If I return last_letter then I get an l

推荐答案

我将改为解释递归算法本身.以应该产生tupni"的输入"为例.您可以通过

I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by

  • 如果字符串为空或单个字符,则原样返回.
  • 否则,
  1. 删除第一个字符.
  2. 反转剩余的字符串.
  3. 将上面的第一个字符添加到反转字符串中.
  4. 返回新字符串.

这篇关于编写一个递归函数来反转输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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