java - Java 递归反转字符串

标签 java string recursion

我尝试在 Java 中递归地反转字符串,但我只得到最后一个字符作为输出。

网上查了一下,大部分代码都修改了输入字符串。我正在尝试构建从空字符串到反转字符串的输出。请告诉我我的程序出了什么问题。

class reverseStringRecursion
{
    public static void main(String args[])
    {
        System.out.println(reverse());
    }

    public static String reverse()
    {
        String strInput = " Hello I am my name.";
        String output = "";
        return recursiveHelper(strInput, 0, output);
    }

    public static String recursiveHelper(String strInput, int index, String output)
    {
        if(index == (strInput.length() - 1 ))
            output += strInput.charAt(index) + "";
        else
            output+= recursiveHelper(strInput, index + 1, output) +"";

        return output;
    }
}

上面的代码返回输出“.”仅此而已。请帮忙。

最佳答案

其他人已经很好地解释了为什么您的代码不起作用。为了进行比较,这里有一个带有一些注释的工作版本:

public static void main(String args[])
{
    System.out.println(reverse("Hello I am my name."));
}

public static String reverse(String text)
{
    // Base case:
    // If the string is empty, we're done.
    if (text.length() == 0) {
        return "";
    } else {
        // reverse("hello") = reverse("ello") + "h"
        return reverse(text.substring(1)) + text.charAt(0);
    }
}

关于java - Java 递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766383/

相关文章:

java - 捕获异常时不定式递归

java - 了解 Spring 中的 SessionFactory

java - 匹配java中字符串的模式

java - JFrame 的 setSize 不起作用

c - 在 sscanf 中指定可变字段宽度

python - 如何在使用python匹配条件后从列表的开始迭代开始for循环

Java递归进阶

java - 我如何在 Java 中组合两个对象?

c - qsort 一个字符串数组,比较

javascript - jQuery - 如果选中多个复选框,并且为每个复选框添加一个字符串到文本框