String Reversal
Question: The string type in C# doesn't have a Reverse() method. How would you write it?
Answer: The answer is fairly straightforward - convert the string to a char array then use a standard swap routine on the first half of the characters. Here's the C# code to do it:
public static void Main()
{
string aa = "damien";
aa = ReverseString(aa);
Console.WriteLine(aa);
}
public static string ReverseString(string s)
{
var chars = s.ToCharArray();
var n = chars.Length;
for(var i=0; i<n/2; i++)
{
var temp = chars[i];
chars[i] = chars[n - 1 -i];
chars[n - 1- i] = temp;
}
return new string(chars);
}
01 May 2008 Damien Wintour








[...] would you reverse a string in-place? See my earlier article on [...]