Reversing the sequence of words in a string with minimal temporary storage

using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string str = "I like computers";

            char[] chArray = str.ToCharArray();

            //reversing the entire array

            Array.Reverse(chArray);

            for (int i = 0, j = 0; i < chArray.Length; i++)

            {

                if (i < chArray.Length – 1)

                {

                    if (chArray[i] == ‘ ‘)

                    {

                        for (int p = j, q = i – 1; p < q; p++, q–)

                        {

                            char temp = chArray[p];

                            chArray[p] = chArray[q];

                            chArray[q] = temp;

                        }

                        j = i + 1;

                    }

                }

                else

                {

                    for (int p = j, q = i; p < q; p++, q–)

                    {

                        char temp = chArray[p];

                        chArray[p] = chArray[q];

                        chArray[q] = temp;

                    }

                }

            }

            for (int i = 0; i < chArray.Length; i++)

            {

                Console.Write(chArray[i]);

            }

            Console.WriteLine();

        }

    }

}
 
computers like I
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s