Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Extension Methods to Reverse a String and StringBuilder Object

4.88/5 (9 votes)
1 Jan 2011CPOL 19.2K  
And even simpler, faster and better would be this:public static string ReverseCA(string s) { char[] chars=s.ToCharArray(); Array.Reverse(chars); return new string(chars);}Whatever the string's length, only three objects get created; and all characters get copied three...
And even simpler, faster and better would be this:

C#
public static string ReverseCA(string s) {
    char[] chars=s.ToCharArray();
    Array.Reverse(chars);
    return new string(chars);
}

Whatever the string's length, only three objects get created; and all characters get copied three times, no more, no less. For the same 80-char test string it is 14 times faster than John's original.

Note: if you have to reverse a StringBuilder, the other alternative is probably the better one.

:)

License

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