0

我在 C# 中有一个很好的谜语(我是初学者)。我需要递归地保留一个字符串(在一个方法内)。我试过了:

 public static void ReverseString(string str)
    {
        if(str.Length > 0)
        {
            char ch = str[str.Length-1];
            ReverseString(str.Substring(0,str.Length-2));
            Console.Write(ch);
        }
    }

但它不起作用。我只能更改if. (str[str.Length-1]str.Substring(0,str.Length-2)

我的错误是什么?谢谢

4

2 回答 2

9
public static void ReverseString(string str)
{
    if(!String.IsNullOrEmpty(str))
    {
        char ch = str[0];
        ReverseString(str.Substring(1));
        Console.Write(ch);
    }
}

为了解释发生了什么,最里面的调用Console.Write首先被执行,因为递归最终成为字符串的结尾。然后当堆栈开始关闭时,它会打印较早的字符。

于 2013-09-09T20:15:12.570 回答
2

看起来这个函数应该以相反的顺序将字符串打印到控制台。在使用递归时,您应该首先假设该函数完成了它应该做的事情并围绕它进行编码。确保使用较小的数据集完成任何递归调用。在这种情况下,一个较短的字符串。

public static void ReverseString(string str)    // example str="cat"
{
    if(str.Length > 0)
    {
        // grabs the last charactor        "t"
        char ch = str[str.Length-1]; 

        // prints the first n-1 charactors in reverse order   "ac"
        ReverseString(str.Substring(0,str.Length-2));

        // prints that last charactor      "t" leads to "act"... not quite right
        Console.Write(ch);
    }
}

如果您不允许(为了练习)更改最后一行,您可以试试这个。

public static void ReverseString(string str)    // example str="cat"
{
    if(str.Length > 0)
    {
        // grabs the first charactor        "c"
        char ch = str[0]; 

        // prints the last n-1 charactors in reverse order   "ta"
        ReverseString(str.Substring(1));

        // prints that last charactor      "c" leads to "tac"... Yeay!!
        Console.Write(ch);
    }
}
于 2013-09-09T20:16:41.170 回答