Friday, 29 November 2019

Reverse string using Recursion and loop in c#

Method I. 

       ///// Call- ReverseString('abcdefg');

        //Recursion method; simple, for small strings 
        public string ReverseString(string str)
        {
            if (str.Length <= 1) return str;
            else return ReverseString(str.Substring(1)) + str[0];
        }

     ///// Result- ReverseString - gfedcba


Method II. 

       ///// Call- ReverseString('gfedcba', 0);

       //Recursion method; Need to starting index as 0,  for long strings
        public string ReverseString(string str, int Chrindex)
        {
            char[] chr = str.ToCharArray();
            int len = chr.Length;
            if (Chrindex < len / 2)
            {
                char c = chr[Chrindex];
                chr[Chrindex] = chr[len - Chrindex - 1];
                chr[len - Chrindex - 1] = c;
                Chrindex++;
                return ReverseString(new string(chr), Chrindex);
            }
            else
            {
                return new string(chr);
            }
        }

     ///// Result- ReverseString - gfedcba
Method III.

       ///// Call- ReverseString('abcdefg');

        //Using Another array, need to traverse full array. 
        public string ReverseString(string str)
        {
            char[] chr = str.ToCharArray();
            char[] result = new char[chr.Length];
            for (int i = 0, j = str.Length - 1; i < str.Length; i++, j--)
            {
                result[i] = chr[j];
            }
            return new string(result);
        }

     ///// Result- ReverseString - gfedcba

Method IV.

       ///// Call- ReverseString('abcdefg');

      //Using swap method; need to traverse only half of the array. 
        public string ReverseString(string str)
        {
            char[] chr = str.ToCharArray();
            for (int i = 0, j = str.Length - 1; i < j; i++, j--)
            {
                char c = chr[i];
                chr[i] = chr[j];
                chr[j] = c;
            }
            return new string(chr);
        }

     ///// Result- ReverseString - gfedcba


No comments:

Post a Comment

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...