簡體   English   中英

如何在 c# 中將數組的所有元素從左側移動到右側

[英]How do I shift all of the elements of an array from the left side to the right side in c#

我正在嘗試將數組的元素從最左邊一直交換到最右邊。

所以數組看起來像這樣:1234567

我希望 output 是這樣的:7654321

我已經嘗試過了,但它所做的只是將左側的最后一位數字移動到右側,而沒有其他數字。

    static int[] ShiftArray(int[] array)
    {
        int[] temp = new int[array.Length];
        for (int index = 0; index < array.Length; index++)
        {
            temp[(index + 1) % temp.Length] = array[index];
        }

        return temp;
    }

感謝您的任何建議!

如果要更改數組本身的順序(不創建新數組),可以使用以下命令:

Array.Reverse(array);

您可以使用System.Linq中的Reverse方法。

return array.ToList().Reverse().ToArray();

為什么不按降序遍歷數組?

for(int i = array.length - 1; i >= 0; i--)
{
    // do something
}

如果您不想使用任何預建的 .NET 功能,您可以嘗試以下操作:

using System;

public class Program
{
    public static void Main()
    {
        int[] array = new int[]{1, 2, 3, 4, 5, 6, 7};
        int start = 0;
        int end = array.Length - 1;
        while (start < end)
        {
            int temp = array[start];
            array[start] = array[end];
            array[end] = temp;
            start++;
            end--;
        }

        Console.WriteLine("Result: {0}", String.Join("", array));
    }
} 

每當您交換數組中的元素時,您都需要一個臨時變量來在執行交換時保存一個元素。

startend變量用於跟蹤您在數組中的位置。 一旦它們相互交叉,您就完成了交換元素。

結果

Result: 7654321

演示

.NET 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM