Paul Kent

.NET Developer (AngularJS, jQuery, C#, Dependency Injection, Unit Testing, Onion Architecture, Azure Cloud)

How many ways can you think of to reverse a string in C#?

It's a seemingly easy programming task but dig a little deeper and it turns out to be a very tricky exercise. Here are three ways a C# programmer might do this using extension methods.

Note: Null checking is omitted for the purpose of demonstration.

All of these work however the Array.Reverse method turns out to be the neatest of the three approaches and also performs well.

But what happens if you wanted to reverse the string such as Les Mise\u0301rables that has an accent on the é? If you run the above code you get the output selbaŕesiM seL with an accent on the 'r' instead of the 'e'.

A better approach to solve this problem uses the .NET API for grapheme cluster iteration which was described as one answer by R. Martinho Fernandes on this StackOverflow post. It takes into account reversing strings which contain surrogate pairs.

The moral of the story is that string manipulation is not a simple as it first might appear to be. In fact there are many gotchas with all the basic data types we take for granted. Here is an excellent video presentation titled Jon Skeet - Stack Overflow Dev Days London 2009 by Jon Skeet that describes how the specification and implementation of basic data types like numbers, strings and dates causes a lot of headaches for Software Developers and is a source of many bugs. Also see Jon's blog titled OMG Ponies!!! (Aka Humanity: Epic Fail) which reiterates what he talks about in his video.

Comments are closed