- Course
- Recursion
- Reverse a string recursively
Reverse a string recursively
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that requests a string from the user and implements a recursive function to reverse a string of characters.
Input
- Jonny
Output
- ynnoJ
Solution
- using System;
- public class ReverseStringRecusively
- {
- public static void Main(string[] args)
- {
- string text = Console.ReadLine();
- Console.WriteLine(Reverse(text));
- }
-
- public static string Reverse(string text)
- {
- if (text.Length <= 1)
- {
- return text;
- }
-
- char firstLetter = text[0];
- string rest = text.Substring(1);
-
- return Reverse(rest) + firstLetter;
- }
- }