Reverse a String using C#

by Edward 06 August 2010 18:49

This week I was asked by a friend how you would reverse a sentence, with minimial effort and that works in all scenarios. This was a nice challenge for me, so started working on something.

I first though of using recursion with a substring method to reverse the sentence, which worked fine, however this looked a bit messy and I thought it might impact on the performance of the program. I searched MSDN and the ASP.NET website for an alternative option, and surprisingly I found an article which Justin Rogers wrote, which did exactly what I was looking for... You can use the 'Array.Reverse()' method that is already provided to you by the .Net framework.

Here is an example of how to efficiently reverse the characters in a string:

static public string Reverse(string str)
{
    char[] charArray = str.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

Input: Hello World
Output: dlroW olleH


The example above is just for demostration. In my case, I was using large strings, therefore this method was the preferred option. In some cases you can use recursion with a substring method, which will be a better choice on performance.

I though I would share Justin's article, so you can read it here.

Tags: , , ,

ASP.NET | Other

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List