zoukankan      html  css  js  c++  java
  • 编程之美的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--;
                }
            }
    
    
    
     
  • 相关阅读:
    JS函数式编程【译】前言
    11.15周总结
    11.13
    11.12
    11.11
    11.10
    11.9
    11.8周总结
    11.6
    11.5
  • 原文地址:https://www.cnblogs.com/Jessy/p/3478207.html
Copyright © 2011-2022 走看看