Thursday, 24 November 2016

Reverse a String word by word

Given a string, reverse it word by word.

input : I like to play with c-sharp.
expected output : c-sharp with play to like I.

  static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string[] arr = s.Split(' ');
            int length = arr.Length;

            // it will hold reverse array
            string[] revArr = new string[length];

            // this index holds index value for new reversed string.
            int index = length - 1;
            for (int j = length - 1; j >= 0; j--)
            {
                revArr[index-j] = arr[j];
            }

            string revString = String.Join(" ", revArr);
            Console.WriteLine(revString);

            Console.ReadLine();

        }



1 comment:

  1. This could work as well. :)

    static void Main (string[] args)
    {
    string input = Console.ReadLine();
    List SeparatedStrings = input.Split(new char[] {' '},
    StringSplitOptions.RemoveEmptyEntries).ToList();

    SeparatedStrings.Reverse();
    input = "";
    foreach(var item in SeparatedStrings)
    {
    input += (item + " ");
    }

    Console.WriteLine(input);
    }

    ReplyDelete

Note: only a member of this blog may post a comment.