I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:
public string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
Had to submit a recursive example:
From above 3.5 Framework
"Best" can depend on many things, but here are few more short alternatives ordered from fast to slow:
Ok, in the interest of "don't repeat yourself," I offer the following solution:
My understanding is that this implementation, available by default in VB.NET, properly handles Unicode characters.
Sorry for long post, but this might be interesting
Results:
Have a look at the wikipedia entry here. They implement the String.Reverse extension method. This allows you to write code like this:
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this: