Tuesday, October 31, 2017

Reverse string without its special characters

Special characters need to stay in place while the entire string is reversed

 //Reverse string without moving any special character from its place
            var input = "ab$cde#x"; //"xe$cdb#a";
            var arr = input.ToCharArray();

            var h = -1;
            var t = -1;
            //Loop - half length of the array with pointer index of array from left
            for (int p = 0; p < arr.Length/2; p++)
            {
                //Find non special character from left
                if (Regex.IsMatch(arr[p].ToString(),"[a-z]") && h < 0) //non special character
                    h = p;

                //Find non special chracter from right
                if (Regex.IsMatch(arr[arr.Length - p - 1].ToString(), "[a-z]") && t < 0) //non special character
                    t = arr.Length - p - 1;


                //If holding two non special chracters then swap them
                if (h >= 0 && t >= 0) //Non special chracters both directions
                {
                    //Swap
                    var temp = arr[h];
                    arr[h] = arr[t];
                    arr[t] = temp;

                    h = -1;
                    t = -1;
                }
                
               



            }

No comments: