This C# program reverses every word of a string and display the reversed string as an output. There are two solution in this tutorial.
In solution 1, I reversed the string with Reverse Metod.
In solution 2, I reversed the string without Reverse Method.
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 28 |
class Program { static string reversString(string str) { char[] letters = str.ToCharArray(); Array.Reverse(letters); return new string(letters); } static void Main(string[] args) { string str; Console.WriteLine(" \n \n *** www.csharp-console-examples.com *** \n\n"); Console.Write("Enter string :"); str = Console.ReadLine(); Console.WriteLine("***************************"); Console.Write(reversString(str)); Console.ReadLine(); } } |
C# reverse string without using function
Alternative Solution 2: (Reverse string in c# using for loop)
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Program { static string reversString(string str) { string[] words = str.Split(' '); string reversedString = ""; for (int i = words.Length-1; i >=0 ; i--) { String word = words[i]; String reverseWord = ""; for (int j = word.Length - 1; j >= 0; j--) { /* The charAt() function returns the character * at the given position in a string */ reverseWord = reverseWord + word[j]; } reversedString = reversedString + reverseWord + " "; } return reversedString; } static void Main(string[] args) { string str; Console.WriteLine(" \n \n *** www.csharp-console-examples.com *** \n\n"); Console.Write("Enter string :"); str = Console.ReadLine(); Console.WriteLine("***************************"); Console.Write(reversString(str)); Console.ReadLine(); } } |
Output: