Click here to Skip to main content
11,640,599 members (64,965 online)
Click here to Skip to main content

Tagged as

Extension Methods to Reverse a String and StringBuilder Object

, 2 Jan 2011 CPOL 2.9K
Rate this:
Please Sign up or sign in to vote.
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--;
        }
    }
}
 
<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) ASTI Transportation Inc.
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...

v//

You may also be interested in...

Comments and Discussions

 
GeneralUnsafe string manipulation is a very bad idea: http://blogs.... Pin
Richard Deeming4-Jan-11 9:41
memberRichard Deeming4-Jan-11 9:41 
GeneralEven without unsafe there is no denying that the methods I h... Pin
jfriedman2-Jan-11 12:17
memberjfriedman2-Jan-11 12:17 
GeneralI've never had to use unsafe code in my .Net apps. Speed is... Pin
John Simmons / outlaw programmer1-Jan-11 23:23
mvpJohn Simmons / outlaw programmer1-Jan-11 23:23 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 2 Jan 2011
Article Copyright 2011 by jfriedman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid