Your general idea is correct, but you are not quite there.
When using recursion, code first the case where recursion isn't needed. When reversing a string, what is the trivial case? Well, when the string is empty or is only one character long. Ok, lets do that:
public static string Reverse(string s)
{
if (s.Length <= 1)
return s;
//do something else
}
Ok, now, if s
isn't empty, how do we reverse recursively? Well, let's think about what should be returned in the current step. Obviously, if we want to reverse s
, whatever we return, we know that the first letter needs to be the last letter of s
. Ok, lets do that and see where it takes us:
public static string Reverse(string s)
{
if (s.Length <= 1)
return s;
return s[s.Length - 1] + //something
}
And what is that something? Well it has to be the reverse of s
without the last letter, we already took care of that one, remember? But... oh wait! I know how to reverse a string already, don't I? Reverse(s.Substring(0, s.Length - 1)
(isn't recursion magical?)
Et violá:
public static string Reverse(string s)
{
if (s.Length <= 1)
return s;
return s[s.Length - 1] + Reverse(s.Substring(0, s.Length - 1));
}
You didn't even need switch
and else
.