How do I reverse a string?

Category: System, viewed: 2K time(s).

In the following example you'll see how to reverse a string. We use the Array.Reverse() method to reverse the string. First we need to convert the string to char[] and then calling the Array.Reverse method and passes the character array. After this method reverse the array order we create a new string from this character array.

using System;

namespace Kodecsharp.Example.System
{
    class ReverseString
    {
        public static void Main(string[] args)
        {
            string text = "The quick brown fox jumps over the lazy dog";
            char[] c = text.ToCharArray();

            Array.Reverse(c);

            string reversedText = new string(c);
            Console.WriteLine("Reversed Text = " + reversedText);
            Console.ReadLine();
        }
    }
}

Here is the output of the snippet above:

Reversed Text = god yzal eht revo spmuj xof nworb kciuq ehT
Powered by Disqus