#392 – Reversing a String Using the Reverse Method

Starting with .NET 3.5, you can use a number of extension methods that are part of the System.Linq namespace to act upon any type that implements IEnumerable<T>.  This includes the string type in C# (System.String), which implements IEnumerable<char>.

One of the most useful extension methods that comes with Linq is the Reverse method (Enumerable.Reverse<TSource>).  Because this is an extension method, you can use it on an instance of a string as if it were an instance method.

            string funnyMan = "Roscoe Arbuckle";

            string backwardsGuy = new string(funnyMan.Reverse().ToArray());

Because Reverse returns an object of type ReverseIterator<char>, we need to convert it back to an array and then use the array to instantiate a new string.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #392 – Reversing a String Using the Reverse Method

  1. thom311 says:

    I don’t think that this is a good way to do it, because it reverses the individual char instances, i.e. the UTF-16 code points. If your string contains any unicode characters outside the BMP this will swap the order of the lower and higher surrogate pairs.

    • Sean says:

      You’re right, the surrogate pair will get it’s characters swapped. The Reverse method uses the string type’s iterator, which returns a single (2-byte) char at a time.

      If you want correct string reversal that is truly Unicode-aware, you can use Microsoft.VisualBasic.Strings.StrReverse(). This function will correctly handle the surrogate pairs.

      In practice, though, you’re not likely to see characters beyond the BMP, even in software used internationally. BMP supports nearly all modern languages. I work on a software project that is localized for a number of different languages, including Asian languages, and we’ve never seen a user enter a character beyond the BMP.

      But to be complete, you could either ensure that all of your algorithms completely support Unicode, including surrogate pairs. Or you could block input of characters in other planes, e.g. by using the Char.IsSurrogate() method.

  2. Pingback: #773 – Reversing a String that Contains Unicode Characters Expressed as Surrogate Pairs « 2,000 Things You Should Know About C#

  3. kai zhou says:

    Nice work, thank you Sean and thom311.

  4. Naresh says:

    Best way of reversing a string, Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: