-4

I don't know how i don't want a direct answer I want to know how can i. Many thanks in advance.

class Program
{
    static void Main(string[] args)
     {
      Console.WriteLine("Enter a word or sentence to be reversed: ");
      string str = Console.ReadLine();
      Console.WriteLine("**********");
      Console.WriteLine("Your input is: ");
      Console.WriteLine(str);
      Console.ReadLine();//to give a little bit space between the outputs
      Console.WriteLine("************");
      Console.WriteLine("And it will be reversed as : ");
      //call the Recursive Function in the class Recursive
      str = Recursive.Recursive_Func(str);
      Console.WriteLine(str);
      Console.ReadLine();
   }
}


We use Substring to print from the n-1 index in the string and end it with the first index in the string which is [0].

class Recursive
{
    public static string Recursive_Func(string str)
    {
        if (str.Length <= 1) //the program base case
        {
            return str;
        }
        else
        {
            return Recursive_Func(str.Substring(1)) + str[0];
        }
    }
}
Jimi
  • 29,621
  • 8
  • 43
  • 61
beter dark
  • 9
  • 1
  • 1
  • 1
    Usually one can surmise the question is "How can I fix my broken program?" As far as I can tell here, the program is correct. It reverses a string using recursion. What is your actual question? How can you *what*? – Mike Zboray Nov 25 '17 at 22:18
  • 1
    See this: [Best way to reverse a string](https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string) – Jimi Nov 26 '17 at 00:52

2 Answers2

3

I believe this solution is simpler and easier to understand than the other answer.

 public static string MyReverse(string s)
 {
     if (s.Length == 1)
     {
         return s;
     }
     var firstLetter = s[0];
     return MyReverse(s.Substring(1)) + firstLetter;
 }
Neuron
  • 5,141
  • 5
  • 38
  • 59
1

Your implementation is naïve and slow but it is recursive, and it works. The below implementation converts the string into a char array, uses a recursive helper method to reverse the chars in-place, and converts the reversed array back into a string:

class Recursive
{
    public static string StrRev(string s)
    {
        if (string.IsNullOrEmpty(s)) return s;
        var a = s.ToCharArray();
        return new string(CharArrRev(a, 0, a.Length - 1));
    }

    private static char[] CharArrRev(char[] a, int i, int j)
    {
        if (i >= j) return a;
        var c = a[i]; a[i] = a[j]; a[j] = c;
        return CharArrRev(a, i + 1, j - 1);
    }
}
dumetrulo
  • 1,993
  • 9
  • 11