How to reverse string in C#
Kirtesh Shah
Select an image from your device to upload
//For high-performance
string input = "Hello World";
Span<char> buffer = stackalloc char[input.Length];
for (int i = 0; i < input.Length; i++)
{
buffer[i] = input[input.Length - 1 - i];
}
string reversed = new string(buffer);
Console.WriteLine(reversed);
Method 1: Using ToCharArray() and Array.Reverse()
string str = “hello”;char[] charArray = str.ToCharArray();Array.Reverse(charArray);string reversed = new string(charArray);Console.WriteLine(reversed); // Output: “olleh”
Method 2: Using LINQusing System;using System.Linq;
string str = “world”;string reversed = new string(str.Reverse().ToArray());Console.WriteLine(reversed); // Output: “dlrow”