After doing a lot of coding and finally getting my program to do what I wanted I decided to take a break and try something new (for me).
One thing I never had to do for any application is reverse a string. As with anything I never did before I decided to give it a try, so I cooked up a few functions.
Reverse1 below is the most basic way of doing it, but is the slowest. Since in .NET string are immutable (See Jon's Article for details) each time we concatenate it will create a new string object to keep our updated text. This can be very slow for large text blocks.
Reverse2 is a StringBuilder version which uses the power of mutable strings to avoid our performance problem above.
Reverse3 is an example I found trying to look for alternatives to my first two functions. (Thanks Justin Rogers for your post)
My Reverse String Examples
private static void Reverse1()
{
string Data = "hello world";
string Data2 = string.Empty;
// Reverse using strings
for (int i = Data.Length - 1; i >= 0; i--)
{
Data2 += Data.Substring(i, 1);
}
Console.WriteLine("Basic Strings: " + Data2);
}
private static void Reverse2()
{
string Data = "hello world";
StringBuilder sb = new StringBuilder();
// Reverse - String Builer for Performance
for (int i = Data.Length - 1; i >= 0; i--)
{
sb.Append(Data.Substring(i, 1));
}
Console.WriteLine("StringBuilder: " + sb.ToString());
}
private static void Reverse3()
{
string Data = "hello world";
char[] DataArray = Data.ToCharArray();
Array.Reverse(DataArray); // reverse
string Output = new string(DataArray); // back to string
Console.WriteLine("Array Reverse: " + Output);
}