65.9K
CodeProject is changing. Read more.
Home

Extension Methods to Reverse a String and StringBuilder Object

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (5 votes)

Jan 1, 2011

CPOL
viewsIcon

12013

This is an alternative to "Extension Methods to Reverse a String and StringBuilder Object".

Less code, and much faster, would be:

public static string ReverseSB(string text) {
    int len = text.Length;
    if (len>1) {
        StringBuilder sb=new StringBuilder(text);
        int pivotPos=len/2;
        len--;
        for (int i = 0; i < pivotPos; i++) {
            int j=len-i;
            char temp=sb[i];
            sb[i]=sb[j];
            sb[j]=temp;
        }
        text=sb.ToString();
    }
    return text;
}

or its extension-method variant. Tested on a 80-char string, it is 8 times faster. The reason should be clear: John's code creates 6 strings for each character pair, as each SubString, Remove, Insert method generates a new string object, copying the relevant characters.

:)