编程之美的2.17,数组循环移位 & 字符串逆转(反转) Hello world Welcome => Welcome world Hello

代码如下:(类似于编程之美的2.17,数组循环移位)

 
 static void Main(string[] args)
        {

            string input = "Hello World Welcome";
            char[] tempArray = input.ToCharArray();          

            string result = RightShift(tempArray, 0, tempArray.Length-1);         
        }

        public static string RightShift(char[] arrary, int startIndex, int endIndex)
        {
            Reverse(arrary, 0, endIndex);

            startIndex = endIndex = 0;

            while (startIndex < arrary.Length - 1)
            {
                if (arrary[startIndex] == ' ')
                {
                    startIndex++;
                    endIndex++;
                    continue;

                }
                else if (arrary[endIndex] == ' ')
                {
                    int currentIndex = endIndex;
                    Reverse(arrary, startIndex, endIndex - 1);
                    startIndex = endIndex = currentIndex;
                }
                else if (endIndex == arrary.Length - 1)
                {
                    int currentIndex = endIndex;
                    Reverse(arrary, startIndex, endIndex);
                    startIndex = endIndex = currentIndex;
                }
                else
                {
                    endIndex++;
                }
            }

            StringBuilder builder = new StringBuilder();
            foreach (char item in arrary)
            {
                builder.Append(item);
            }

            return builder.ToString();

        }

        public static void Reverse(char[] arrary, int start, int end)
        {
            while (start < end)
            {
                char temp = arrary[start];
                arrary[start] = arrary[end];
                arrary[end] = temp;

                start++;
                end--;
            }
        }
 

 

 

 

你可能感兴趣的:(Hello world)