We will learn to create our “C# String Reverse Function” to get the length of the string, to reverse the string, to copy string by in this example
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Program { static string ReverseString(string str) { int len = str.Length; string reversed = ""; for (int i = 0; i < len; i++) { reversed += str[len - (i+1)]; } return reversed ; } static void Main(string[] args) { string myStr="HelloWorld"; string reversed = ReverseString(myStr); Console.WriteLine("Your String:" + myStr); Console.WriteLine("Reversed String:" + reversed); Console.ReadLine(); } } |
Solution 2: We can also reverse a string using recursion function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Program { public static string ReverseString(string str) { if ((str == null) || (str.Length <= 1)) return str; return ReverseString(str.Substring(1)) + str[0]; } static void Main(string[] args) { string myStr="Hello World"; string reversed = ReverseString(myStr); Console.WriteLine("Your String:" + myStr); Console.WriteLine("Reversed String:" + reversed); Console.ReadLine(); } } |
Output: