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?
Reverse String in Java, Easiest Way The easiest way to reverse a string in Java is to use the built-in reverse() function of the StringBuilder class.
By Using StringBuilder StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.
We can use the StringBuilder. reverse() method to reverse a Java string efficiently. Alternatively, we can also use the StringBuffer. reverse() method.
public static string Reverse( string s ) { char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); return new string( charArray ); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With