C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ReverseString: This method receives a string parameter—this is the string in which you wish to reverse the order of the letters.
Reverse: The method calls Array.Reverse to modify the order of the chars. Reverse cannot be used on a string directly.
StaticArray.ReverseToCharArray: The method copies to an array using ToCharArray. It returns a string with the new string constructor.
Char ArrayString ConstructorC# program that reverses strings
using System;
static class StringHelper
{
/// <summary>
/// Receives string and returns the string with its letters reversed.
/// </summary>
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
class Program
{
static void Main()
{
Console.WriteLine(StringHelper.ReverseString("framework"));
Console.WriteLine(StringHelper.ReverseString("samuel"));
Console.WriteLine(StringHelper.ReverseString("example string"));
}
}
Output
krowemarf
leumas
gnirts elpmaxe
Version 1: This method uses ToCharArray and Array.Reverse. It is short and simple, probably good enough for most programs.
Version 2: This version allocates an empty char array, and iterates backwards through the string and assigns elements in the array.
Result: The iterative method ReverseStringDirect is faster—nearly twice as fast. It does not use Array.Reverse or ToCharArray.
C# program that benchmarks string reverse methods
using System;
using System.Diagnostics;
class Program
{
public static string ReverseString(string s)
{
char[] array = s.ToCharArray();
Array.Reverse(array);
return new string(array);
}
public static string ReverseStringDirect(string s)
{
char[] array = new char[s.Length];
int forward = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
array[forward++] = s[i];
}
return new string(array);
}
static void Main()
{
int sum = 0;
const int _max = 10000000;
Console.WriteLine(ReverseString("test"));
Console.WriteLine(ReverseStringDirect("test"));
// Version 1: reverse with ToCharArray.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
sum += ReverseString("programmingisfun").Length;
}
s1.Stop();
// Version 2: reverse with iteration.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
sum += ReverseStringDirect("programmingisfun").Length;
}
s2.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds);
Console.WriteLine(s2.Elapsed.TotalMilliseconds);
}
}
Output
tset
tset
597.2342 ms ReverseString
392.2862 ms ReverseStringDirect