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

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...