Click here to Skip to main content
15,118,508 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 2 Jan 2011

Tagged as

Stats

8.3K views

Extension Methods to Reverse a String and StringBuilder Object

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
2 Jan 2011CPOL
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
C#
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.

C#
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--;
        }
    }
}

<pre lang="cs">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);
}




License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jfriedman
Software Developer (Senior)
United States United States
Livin in a lonely world, caught the midnight train going anywhere... Only thing is it was a runaway train... and it ain't ever goin back...
мала ка на хари, Trahentes ex exsilium

Comments and Discussions

 
GeneralUnsafe string manipulation is a very bad idea: http://blogs.... Pin
Richard Deeming4-Jan-11 10:41
mveRichard Deeming4-Jan-11 10:41 
GeneralEven without unsafe there is no denying that the methods I h... Pin
jfriedman2-Jan-11 13:17
Memberjfriedman2-Jan-11 13:17 
GeneralI've never had to use unsafe code in my .Net apps. Speed is... Pin
#realJSOP2-Jan-11 0:23
mva#realJSOP2-Jan-11 0:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.