编写一个反转输入字符串的递归函数 [英] Write a recursive function that reverses the input string
问题描述
我一直在读C ++ For Everyone一书,其中一个练习说写一个函数 string reverse(string str)
其中返回值是 str
。
有人可以写一些基本代码并向我解释吗?我昨天一直盯着这个问题,不能弄清楚。我已经得到的最远的函数返回 str
的第一个字母(我仍然不知道它是怎么发生的)
这是我的(在发布此问题后一小时):
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。有人帮我在这里
如果我返回字
而不是返回str_copy
然后我得到一个 w
如果我返回last_letter
,那么我得到一个 l
我有两分钟,所以我将解释递归算法本身。以输入为例,它应该产生tupni。
- 如果字符串为空或单个字符,则返回不变。
- 否则
- 删除第一个字符。
- 颠倒剩余的字符串。
- 将以上第一个字符添加到反转的字符串中。
- 返回新的字符串。
ul>
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 ofstr
.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; }
If I enter "Wolf", it returns Wol. Somebody help me out here If I
return word
instead ofreturn str_copy
then I get aw
If Ireturn last_letter
then I get anl
解决方案I've got two minutes so I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by
- If the string is empty or a single character, return it unchanged.
- Otherwise,
- Remove the first character.
- Reverse the remaining string.
- Add the first character above to the reversed string.
- Return the new string.
这篇关于编写一个反转输入字符串的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!