Extension Methods to Reverse a String and StringBuilder Object






4.88/5 (9 votes)
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.
:)