Reverse String in C#
spirit1 shows how to reverse string in C# quickly using bitwise operations and XOR.
"i knew that there was a handy little way of switching 2 values using something with XOR without using a 3rd variable. i just couldn't remember it... so i went googling... it sure was faster than going through my books :)) and voila... XOR 2 values bitwise 3 times and they're switched."
After a while the original post was updated with even faster function which makes use of a char array of fixed length so string copy in memory is avoided:
public string Reverse(string str)
{
int len = str.Length;
char[] arr = new char[len];
for (int i = 0; i < len; i++)
{
arr[i] = str[len - 1 - i];
}
return new string(arr);
}
Monday, March 20, 2006 12:10 AM