11,934,389 members (51,606 online)
Alternative Tip/Trick
alternative version

14.8K views
1 bookmarked
Posted

# Reverse of a string without using the Reverse function in C# and VB

, 23 Jul 2011 CPOL
 Rate this:
Yet some another way to reverse strings is given below. Take a look:private static string Reverse(string str){ if (str.Length == 1) return str; else return str[str.Length - 1] + Reverse(str.Substring(0, str.Length - 1));}and:public static string Reverse(string...

Yet some another way to reverse strings is given below. Take a look:

```private static string Reverse(string str)
{
if (str.Length == 1)
return str;
else
return str[str.Length - 1] + Reverse(str.Substring(0, str.Length - 1));
}```

and:

```public static string Reverse(string x)
{
char[] charArray = new char[x.Length];
int len = x.Length - 1;
for (int i = 0; i <= len; i++)
charArray[i] = x[len - i];
return new string(charArray);
}```

and using bitwise XOR:

```public static string ReverseXor(string s)
{
char[] charArray = s.ToCharArray();
int len = s.Length - 1;

for (int i = 0; i < len; i++, len--)
{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}

return new string(charArray);
}```

In comparison of all of these three code snippet second way is faster that XOR and recursive implementation. So I will go for it. I will suggest you to recommend an old but excellent article focusing the performance of reversing algorithm.
take a look there-[Performance: Fastest string reversing algorithms][^].

Apart it I will always go for `Array.Reverse` for reverse process because its simplest and fastest in all of them.

## Share

 Software Developer India
Microsoft Student Partner | CS Student | MCTS | CP MVP | Crazy Learner | Dreamer

An Indian, who loves his country, believes in freedom, He is an enthusiast Techie and crazy learner. He is passionate about Technologies and social media. He holds bachelor degree of CS in Information Technology and now pursuing Master degree in Computer Application.

He always excited and keen Interested in learning and sharing knowledge. He loves to write blog, learn new things, listen music, taking arts and Playing Games..

He keep himself on the desk of his imagination, hanging around with some inceptions.