Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

Reverse String in C#

spirit1 shows how to reverse string in C# quickly using bitwise operations and XOR.


"i knew that there was a handy little way of switching 2 values using something with XOR without using a 3rd variable. i just couldn't remember it... so i went googling... it sure was faster than going through my books :)) and voila... XOR 2 values bitwise 3 times and they're switched."


After a while the original post was updated with even faster function which makes use of a char array of fixed length so string copy in memory is avoided:


public string Reverse(string str)
{
    int len = str.Length;
    char[] arr = new char[len];

    for (int i = 0; i < len; i++)
    {
        arr[i] = str[len - 1 - i];
    }

    return new string(arr);
}

Related Posts:

Monday, March 20, 2006 12:10 AM

Comments

# re: Reverse string in C#
send the code for reversing the code

10/1/2006 12:03 PM by abdul

# re: Reverse string in C#
i want reverse string in c#

2/20/2007 7:51 AM by bhaskarrao

# re: Reverse string in C#
pls send this

3/15/2007 10:22 AM by m.vijaydeep

# re: Reverse string in C#
please send the code for this question-

WRITE A PRG TO PASS A NAME THROUGH A PARAMETERIZED CONSTRUCTOR AND PRINT IT IN REVERSE ORDER AND DISPLAY IT BY USING SUITABLE MEMBER FUNCTIONS.

5/26/2007 11:35 AM by IRA

# re: Reverse string in C#
char[] str = "abcdef".ToCharArray();
Array.Reverse(str);
string strReversed = new string(str);

Console.WriteLine( "Reversedstring : " + strReversed);

8/13/2007 11:43 AM by Sahebjade Page

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)