Extension Methods to Reverse a String and StringBuilder Object
This was already decided here in another thread...Using unsafe code and just copying the chars you get much better performance...You could also XORcharArray[i] ^= charArray[len];charArray[len] ^= charArray[i];charArray[i] ^= charArray[len];But something like this is...
This was already decided here in another thread...
Using unsafe code and just copying the chars you get much better performance...
You could also XOR
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
But something like this is actually faster due to less operations not allocations.
public static unsafe void Reverse(ref String string)
{
fixed(char* chars = string)
{
int c = 0, d = string.Length - 1;
while(c < d)
{
char t = chars[d];
chars[d] = chars[c];
chars[c] = t;
c++;
d--;
}
}
}
public static void Reverse(ref String string)
{
char[] chars = string.ToCharArray();
int c = 0, d = string.Length - 1;
while(c < d)
{
char t = chars[d];
chars[d] = chars[c];
chars[c] = t;
c++;
d--;
}
string = new string(chars);
}