Pages

Friday, December 7, 2012

Reverse of a string by words C# example


string-reversal-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 reversal, like


Hello How Are You
Becomes
You Are How Hello


Reversing characters inside a word is a different story.
Some people find it 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.
Assumption:
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
0Hello
1World
2Let's
3Reverse
4The
5String

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

reverse-string-pyramid

No comments:

Post a Comment