Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reverse a string

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?

like image 659
Guy Avatar asked Oct 23 '08 00:10

Guy


People also ask

What is the fastest way to reverse a string?

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.

What is the method to reverse a string?

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.

Can efficiently reverse a string using?

We can use the StringBuilder. reverse() method to reverse a Java string efficiently. Alternatively, we can also use the StringBuffer. reverse() method.


2 Answers

public static string Reverse( string s ) {     char[] charArray = s.ToCharArray();     Array.Reverse( charArray );     return new string( charArray ); } 
like image 124
PeteT Avatar answered Sep 20 '22 15:09

PeteT


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.

like image 43
R. Martinho Fernandes Avatar answered Sep 20 '22 15:09

R. Martinho Fernandes