Sunday, September 4, 2011

Reverse of a string by words C# example


Reverse of a string in C#, VB .Net, or C++ is pretty easy. Please not that we are talking about a word by word string reversal, for example

Hello How Are You
You Are How Hello

Reversing characters inside a word is a different story, not covered here.
Some people find word order reversal difficult, so I'm putting the C# example code here.

class Program
        public static string reverseIt(string strSource)
            string[] arySource = strSource.Split(new char[] { ' ' });
            string strReverse = string.Empty;
            for (int i = arySource.Length - 1; i >= 0; i--)
                    strReverse = strReverse + " "  + arySource[i];
            Console.WriteLine("Original: " + strSource);
            Console.WriteLine("Reverse: " + strReverse);

            return strReverse;

        static void Main(string[] args)
            reverseIt("Hello World! Let's Reverse The String");

The algorithm is very simple and it's made easy with constructs provided by .Net framework.
We assume that two words inside a given string will be separated by one white space.

First of all we call Split method on the string which user provided us, we pass in an array of characters which contains only one space, although we can put other characters like tab '\t' as separator in here. The method call 
string[] arySource = strSource.Split(new char[] { ' ' });

When separated, the array arySource will look like as given below

Array IndexWord
0 Hello
1 World
2 Let's
3 Reverse
4 The
5 String

Now we put a for loop, and start iterating from the end of array to beginning of array. The loop will start working from arySource.Length - 1 i.e. 5 in our case and it will keep on moving until value of variable i reaches -1.
In every iteration of loop, we pick a word a and put to the strReverse. The string will be built in a triangle form as given below


One more thing, what happens if we got more than one spaces between the words inside string?
In that case, we can remove empty string entries by calling a different version of string.split method, the call is given below:
string[] arySource = strSource.Split(new char[] { ' ', StringSpli tOptions.RemoteEmptyEntries});

Please feel free to comment and ask any further questions. Remember, same principals can be applied to break string in parts in other languages such as C or C++, although a few adjustments will be needed.

I'm working as a freelance programmer through, my profile clearly reflects what I am made of. Feel free to ping me if you need an Android app for yourself or your employer.


  1. C++ Program to Reverse a Strings

    Reverse a String means reverse the position of all character of String. You can use swapping concept to reverse any string in c++.

  2. this will always add an empty space in the beginning.


Feel free to talk back...