-1

I can find no String.Reverse() in .net that actually returns a string. (Any reason why there is none?) What would the most efficient code (least temp objects created etc) for reversing a string in .net be?

Tim Lovell-Smith
  • 15,310
  • 14
  • 76
  • 93
  • In retrospect, I think I see the answer: the reason there is none, is that it is ambiguous what string.Reverse should do, and therefore a source of surprises and bugs: should it return you all the UTF-16 codepoints of your string in reverse order? Or the UTF-32 codepoints? What about combining marks and ordering? Should it return you unicode text which should visually look like the original string but reversed? Which canonical representation of that? – Tim Lovell-Smith Nov 20 '18 at 21:32

2 Answers2

1

With .NET 4.5 (maybe earlier, I dunno), the framework ships with an extension method to the String class named Reverse.

Reverse() returns an IEnumerable<Char>, which is directly assignable to a String.

So this should work:

string one = "kayak";
string two = (string)(one.Reverse());
Sam Axe
  • 33,313
  • 9
  • 55
  • 89
  • The built in string Reverse was added for .net 3.5. At the Same time MS snuck in REVERSE string into SQL server for SQL Server 2008 and later. – Sql Surfer Sep 14 '16 at 03:02
-1

Try this:

public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47