Reverse Words of a String in C#

Introduction

In this article I show how to reverse the words in a string. Do not confuse this with reversing a string, in other words "John" to "nhoJ". This is different. Basically it reverses the entire string in a paragraph. Like if you have "Hi, I am sharad", the following code will reverse that such that it is "Sharad am I ,HI". So the last word of that string becomes the first word and the first becomes the last, or you can say that the following code reads paragraph string from the last to the first.

I do it in two ways, the first one just uses the split function that splits the string where the space is found, and stores that split array in a string array and then I add a simple logic to print that string on the behalf of its index.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

namespace ConsoleApplication9

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine("Eneter the String:");

            Console.ForegroundColor = ConsoleColor.Yellow;

            string s=Console.ReadLine();

            string [] a = s.Split(' ');

             Array.Reverse(a);

             Console.ForegroundColor = ConsoleColor.Red;

             Console.WriteLine("Reverse String is:");

             for(int i=0;i<=a.Length-1;i++)

                {

                Console.ForegroundColor = ConsoleColor.White;

                Console.Write(a[i]+""+' ');

                }

            Console.ReadKey();

          }

        }

}

Output

reverse-string1.jpg

And for the second way, in this example I am not using the array Reverse function. Just split the string from the space and stored into an array and print that array from the last index to the initial index.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

namespace ConsoleApplication9

{

    class Program

    {

        static void Main(string[] args)

        {

            int temp;

            string s = Console.ReadLine();

            string[] a = s.Split(' ');

            int k = a.Length - 1;

            temp = k;

           for (int i = k; temp >= 0; k--)

            {

                Console.Write(a[temp] + "" + ' ');

                --temp;

            }

            Console.ReadKey();

        }

    }

}

Output

reverse1-string.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all