patterncsharpCritical
Best way to reverse a string
Viewed 0 times
stringwayreversebest
Problem
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:
Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
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?
Solution
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}Code Snippets
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}Context
Stack Overflow Q#228038, score: 853
Revisions (0)
No revisions yet.