w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Get the reverse of a string

Secondary Nav

C# Sharp Recursion : Exercise-14 with Solution

Write a program in C# Sharp to get the reverse of a string using recursion.
Test Data :
Input the string : w3resource
Expected Output
:
The reverse of the string is : ecruoser3w

C# Sharp Code:

using System;
class RecExercise14
    {
        static void Main()
        {
            string str; 
			Console.WriteLine("\n\n Recursion : Get the reverse of a string :");
			Console.WriteLine("----------------------------------------------"); 
			Console.Write(" Input the string : ");
            str = Console.ReadLine();
            str = StringReverse(str);
            Console.Write(" The reverse of the string is : ");
            Console.Write(str);
            Console.ReadKey();
             Console.Write("\n"); 
            
        }

        public static string StringReverse(string str)
        {
            if (str.Length > 0)
                return str[str.Length - 1] + StringReverse(str.Substring(0, str.Length - 1));
            else
                return str;
        }
    }

C# Sharp Practice online:


using System;
class RecExercise14
    {
        static void Main()
        {
            string str; 
			Console.WriteLine("\n\n Recursion : Get the reverse of a string :");
			Console.WriteLine("----------------------------------------------"); 
			Console.Write(" Input the string : ");
            str = Console.ReadLine();
            str = StringReverse(str);
            Console.Write(" The reverse of the string is : ");
            Console.Write(str);
            Console.ReadKey();
             Console.Write("\n"); 
            
        }

        public static string StringReverse(string str)
        {
            if (str.Length > 0)
                return str[str.Length - 1] + StringReverse(str.Substring(0, str.Length - 1));
            else
                return str;
        }
    }

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program