String Reversal in C#
Given a string, return a new string with the reversed order of characters!
For/Foreach Loop
In C#, a string is a sequence of characters. That allows to iterate over characters in a string with a for-loop and a foreach-loop.
public static string Reverse(string str)
{
// Create an empty string.
var reversed = string.Empty;
// Loop through all of the characters of the string.
foreach (var chr in str)
{
// Add the character to the start of the reversed string.
reversed = chr + reversed;
}
return reversed;
}
StringBuilder.Append()
String
objects in C# are immutable. They cannot be changed after they have been created. The major advantage of this structure is that strings
are thread-safe. But, constantly changing strings
can lead to performance issues.
In above string reversal implementation, it seems that in each iteration the reversed variable is modified. However, a new string
object is created after each execution of the loop body. The alternative is to use StringBuilder
, which is a mutable string class. The StringBuilder
doesn't create a new object but appends new data to the current object.
using System.Text;
public static string Reverse(string str)
{
// Create a StringBuilder.
var reversed = new StringBuilder();
// Read character from the end of the string.
for (var i = str.Length - 1; i >= 0; i--)
{
// Append the character to the StringBuilder object.
reversed.Append(str[i]);
}
return reversed.ToString();
}
Array.Reverse()
To reverse the order of the characters in a string we can invoke the Array.Reverse()
method. The method is a static method on the Array
class. The Array.Reverse()
needs an object of Array
type as the input argument.
public static string Reverse(string str)
{
//Turn the string to a char[].
var charArray = str.ToCharArray();
//Reverses the sort of the char[].
Array.Reverse(charArray);
//Creating a string from the char[].
return new string(charArray);
}
LINQ Operators
In the final string reversal implementation, we will use Reverse()
extension method, which belongs to System.Linq
namespace. The Reverse()
operator takes the input sequence and returns the elements in the reverse order in the output sequence.
using System.Linq;
public static string Reverse(string str)
{
return new string(str.Reverse().ToArray());
}
You can download the source code on Github.