Reverse a String in C#

If you need a function to reverse a string in C#, here it is!

private string ReverseString(string InputStr)
{
  char[] Chars = InputStr.ToCharArray();
  int Length = InputStr.Length-1;

  for (int x=0;x<Length;x++,Length--)
  {
    Chars[x] ^= Chars[Length];
    Chars[Length] ^= Chars[x];
    Chars[x] ^= Chars[Length];
  }

  return new string(Chars);
}
  • Share/Bookmark

7 Comments

AnonymousJuly 19th, 2005 at 9:14 pm

umm….. Chars.Reverse()

AnonymousSeptember 5th, 2005 at 8:46 pm

http://www.livejournal.com/users/his_insignifica/10122.html

AnonymousMay 7th, 2006 at 5:41 am

Detailed discussions; do not miss the link in the end to the unmanaged reversal discussion.

IshitaAugust 31st, 2006 at 5:26 pm

Short and too the point. Nice post. Do you know how to write a string palendrome program in C# ?

Mikhail EstevesAugust 31st, 2006 at 10:48 pm

Ishita: There’s a solution here – http://www.csharphelp.com/archives/archive12.html

You could also try something like this (not tested).

public bool isPalindrome (string str)
{
int length = str.Length;
if (length < = 1) return true;
if (str [0] == str [length-1])
{
length = length – 2;
return isPalindrome (str+1);
}
else
return false;
}

BobMarch 2nd, 2007 at 5:07 pm

public static string ReverseString(string input)
{
char[] forward = input.ToCharArray();
StringBuilder reverse = new StringBuilder(input.Length);

for (int i = input.Length – 1; i >= 0; i—)
reverse.Append(forward[i]);

return reverse.ToString();
}

Vyas BharghavaAugust 24th, 2007 at 4:41 pm

public static string Reverse(string str)
{
char[] chars = str.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}

Leave a comment

Your comment