Best way to reverse a string
Here a solution that properly reverses the string "Les Mise\u0301rables"
as "selbare\u0301siM seL"
. This should render just like selbarésiM seL
, not selbaŕesiM seL
(note the position of the accent), as would the result of most implementations based on code units (Array.Reverse
, etc) or even code points (reversing with special care for surrogate pairs).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public static class Test
{
private static IEnumerable<string> GraphemeClusters(this string s) {
var enumerator = StringInfo.GetTextElementEnumerator(s);
while(enumerator.MoveNext()) {
yield return (string)enumerator.Current;
}
}
private static string ReverseGraphemeClusters(this string s) {
return string.Join("", s.GraphemeClusters().Reverse().ToArray());
}
public static void Main()
{
var s = "Les Mise\u0301rables";
var r = s.ReverseGraphemeClusters();
Console.WriteLine(r);
}
}
(And live running example here: https://ideone.com/DqAeMJ)
It simply uses the .NET API for grapheme cluster iteration, which has been there since ever, but a bit "hidden" from view, it seems.
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}