编写一个递归函数来反转输入字符串

2023-03-07C/C++开发问题
3

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

问题描述

我一直在阅读 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. 返回新字符串.

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6