65.9K
CodeProject is changing. Read more.
Home

Extension Methods to Reverse a String and StringBuilder Object

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (9 votes)

Jan 1, 2011

CPOL
viewsIcon

19161

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:
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. :)