Saturday, June 10, 2017

Reverse a given string in C#

In C#, if you are given a string and asked to reverse that string, below code will be helpful for you.

INPUT => VIJAY PANDEY
OUTPUT => YEDNAP YAJIV

Step 1. Create a console application
Step 2. Follow below code

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the string to be reversed :");
            string stringTobeReversed = Console.ReadLine();
            Console.WriteLine(GetReverseString(stringTobeReversed));
            Console.ReadKey();
        }

      #region Method to reverse a given string

        private static string GetReverseString(string str)
        {
            string revstr = string.Empty; // take an empty string to hold the reversed string

            #region using FOR LOOP
            // Start for loop from string length -1 and proceed till the index not equals to -1.
            // Continue decreasing the index

            for (int i = str.Length - 1; i != -1; i--)
            {
                revstr += str[i]; // append each character of the string to the empty string we already have
            }
            return revstr;

            #endregion

            #region Using WHILE LOOP
            // Similarly, we can do this using While loop
            int length = str.Length - 1;
            revstr = string.Empty;
            while (length >= 0)
            {
                revstr += str[length];
                length--;
            }
            return revstr;

            #endregion
        }

        #endregion

   }


No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...