A while back I wrote this post on how to use an extension method to reverse a string of text. The method simply iterated each character in reverse order appending the character to a StringBuilder object, as shown below.
string oldstring = "England";
StringBuilder newString = new StringBuilder();
for (int i = oldString.Length - 1; i >= 0; i--)
{
newString.Append(oldString[i]);
}
There is another way to reverse a string. Enter the LINQ Reverse method which “Inverts the order of the elements in a sequence” the keyword here is sequence. The result of calling the method is “A sequence whose elements correspond to those of the input sequence in reverse order.”
Again the word sequence. As a string object is s sequence of characters the result of the following statement
"Hello".Reverse();
will be IEnumerable, a sequence of characters because the method will see the input as a sequence of characters.
The desired output is to have a single string, so at this point we could iterate the sequence of characters using For loop and appending each character to a StringBuilder like in the previous example.
var oldString = "Hello".Reverse();
StringBuilder newString = new StringBuilder();
for (int i = 0; i < oldString.Length; i++)
{
newString.Append(oldString[i]);
}
But I personally do not see any advantages in doing it this way as there will be additional processing from introducing the extra Reverse() method call.
What we can do here is use the string.Join method to concatenate the character sequence together. The signature of the Join method is string.Join(string, string[]). The first parameter is the separator which is only included in the returned string only if value has more than one element. The second parameter is an array that contains the elements to concatenate, Our sequence of characters needs to be somehow converted to an array.
So to reverse a string we need only a bit of extra LINQ and single line of code **drum roll please**
string.Join(string.Empty,
"Hello".Reverse().Select(s => s.ToString()).ToArray())
Now, I am not recommending any one particular way. I have not compared memory or processor efficiencies between these techniques. What is plain is the difference in the number of lines required.
You must be logged in to post a comment.