65.9K
CodeProject is changing. Read more.
Home

Extension Methods to Reverse a String and StringBuilder Object

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Jan 2, 2011

CPOL
viewsIcon

9597

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 &lt; d)
        {
            char t = chars[d];
            chars[d] = chars[c];
            chars[c] = t;
            c++;
            d--;
        }    
string = new string(chars);
}