BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Reversing a String

Sometimes it can be useful to reverse the contents of a string, character by character. It can come as a surprise to find that there is no native method to achieve this in the .NET framework. However, it is possible with the use of a character array.

Converting to a Character Array

The process for reversing a string requires three steps. The first step is to convert the string into an array of characters that can be reversed. There will be a single element in the array for each character in the original string. To convert the string, you can use the ToCharArray method.

string toReverse = "!desrever eb oT";
char[] characters = toReverse.ToCharArray();

Reversing the Array

The Array class includes a static method named Reverse that can be used to reverse the order of an entire array or of a range of items within an array. As we need to process every character from the original string, we can simply pass the array as a solitary parameter when calling the method.

Array.Reverse(characters);

Rebuilding the String

Now that the array has been reversed, it needs to be converted into the final string. The string class includes a constructor that accepts a character array as a parameter and builds a string by adding each character in order. This suits our purpose exactly. You can now add the following two lines of code to the example and execute the program to see the results.

string reversed = new string(characters);
Console.WriteLine(reversed);                // Outputs: "To be reversed!"
2 October 2007