Sunday, September 4, 2011

Reverse of a string by words C# example

string-reversal-example


Creating a program to generate the reverse of a string variable in C#, VB .Net, or C++ programming is pretty a easy job. Please note that we are talking about a word by word string reversal, for example the string given below 


Hello How Are You

Becomes the following string when read backwards

You Are How Hello


Reversal of characters inside a word is a different story, which is not covered here.
Some people find word order reversal difficult, that's why 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. We can put other characters in this array too like tab character represented by '\t' as separator in here. The string.Split method call comes next.

string[] arySource = strSource.Split(new char[] { ' ' });



The split method is going to find the character which we specified in the parameter and consider it as a divider among the words of the string. 

The results of string separation are returned in an array of string. 
You might use the var keyword here, but it was not an option when this blog post was first written about a decade ago. 

When the string is 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 let us use a for loop, and start iterating from the end of array to beginning of array in reverse order. 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 append it to the strReverse. The string will be built in a triangle form as given below

reverse-string-pyramid

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, C++, Java. A few adjustments will be needed as per the language in question.

5 comments:

  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++.

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

    ReplyDelete

Feel free to talk back...