12 July 2005
Reverse a String in C#
Posted by Mikhail Esteves under: C#; Tips .
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); }
7 Comments so far...
Anonymous Says:
19 July 2005 at 9:14 pm.
umm….. Chars.Reverse()
Anonymous Says:
5 September 2005 at 8:46 pm.
Anonymous Says:
7 May 2006 at 5:41 am.
Detailed discussions; do not miss the link in the end to the unmanaged reversal discussion.
Ishita Says:
31 August 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 Esteves Says:
31 August 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;
}
Bob Says:
2 March 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 Bharghava Says:
24 August 2007 at 4:41 pm.
public static string Reverse(string str)
{
char[] chars = str.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}