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

时间:2022-06-06 05:14:50

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


 static void Main(string[] args)
{ string input = "Hello World Welcome";
char[] tempArray = input.ToCharArray(); string result = RightShift(tempArray, , tempArray.Length-);
} public static string RightShift(char[] arrary, int startIndex, int endIndex)
{
Reverse(arrary, , endIndex); startIndex = endIndex = ; while (startIndex < arrary.Length - )
{
if (arrary[startIndex] == ' ')
{
startIndex++;
endIndex++;
continue; }
else if (arrary[endIndex] == ' ')
{
int currentIndex = endIndex;
Reverse(arrary, startIndex, endIndex - );
startIndex = endIndex = currentIndex;
}
else if (endIndex == arrary.Length - )
{
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--;
}
}