代码如下:(类似于编程之美的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--; } }
做个快乐的自己。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步