In this post, we will learn how to reverse a string using a char array.
Let’s have a look at the implementation in C#.
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 |
class Program { public static String Reverse(String str) { char[] charArr = str.ToCharArray(); int size = charArr.Length; int i; for (i = 0; i < size/2; i++) { char temp = charArr[size-(i+1)]; charArr[size - (i + 1)] = charArr[i]; charArr[i] = temp; } return String.Join("", charArr); } public static void Main() { string str = "Hello, World!!!"; Console.WriteLine(str); str = Reverse(str); Console.WriteLine(str); Console.ReadLine(); } } |
Output:
1 2 3 4 |
Hello, World!!! !!!dlroW ,olleH |