簡體   English   中英

如何在 C# 中交換數組的兩個值?

[英]How can I swap two values of an array in C#?

我有一個 int 數組,其中包含一些從索引 0 開始的值。我想交換兩個值,例如,索引 0 的值應該與索引 1 的值交換。如何在 C# 數組中執行此操作?

使用元組

int[] arr = { 1, 2, 3 };
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(string.Format($"{arr[0]} {arr[1]} {arr[2]}")); // 2 1 3

元組在 C# 7.0 中可用。 請參閱元組類型(C# 參考)

如果你真的只想交換,你可以使用這個方法:

public static bool swap(int x, int y, ref int[] array){
    
        // check for out of range
        if(array.Length <= y || array.Length <= x) return false;
        

        // swap index x and y
        var temp = array[x];
        array[x] = array[y];
        array[y] = temp;    


        return true;
}

x 和 y 是要交換的數組索引。

如果你想與任何類型的數組交換,那么你可以這樣做:

public static bool swap<T>(this T[] objectArray, int x, int y){
    
        // check for out of range
        if(objectArray.Length <= y || objectArray.Length <= x) return false;
        
        
        // swap index x and y
        T temp = objectArray[x];
        objectArray[x] = objectArray[y];
        objectArray[y] = temp ;
        

        return true;
}

你可以這樣稱呼它:

string[] myArray = {"1", "2", "3", "4", "5", "6"};
        
if(!swap<string>(myArray, 0, 1)) {
    Console.WriteLine("x or y are out of range!");
}
else {
    //print myArray content (values will be swapped)
}

您可以創建適用於任何數組的擴展方法:

public static void SwapValues<T>(this T[] source, long index1, long index2)
{
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;
}

僅交換兩個值一次或希望對整個數組執行相同操作:

假設你只想交換兩個並且是整數類型,那么你可以試試這個:

    int temp = 0;
    temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
static void SwapInts(int[] array, int position1, int position2)
{      
    int temp = array[position1]; // Copy the first position's element
    array[position1] = array[position2]; // Assign to the second element
    array[position2] = temp; // Assign to the first element
}

調用這個函數並打印元素

我剛剛寫了類似的東西,所以這里有一個版本

  • 使用泛型,使其適用於整數、字符串等,
  • 使用擴展方法
  • 附帶一個測試類

享受 :)

[TestClass]
public class MiscTests
{
    [TestMethod]
    public void TestSwap()
    {
        int[] sa = {3, 2};
        sa.Swap(0, 1);
        Assert.AreEqual(sa[0], 2);
        Assert.AreEqual(sa[1], 3);
    }
}

public static class SwapExtension
{
    public static void Swap<T>(this T[] a, int i1, int i2)
    {
        T t = a[i1]; 
        a[i1] = a[i2]; 
        a[i2] = t; 
    }
}

可以通過XOR運算符(數學魔法)交換兩個值,如下所示:

public static void Swap(int[] a, int i, int k)
{
    a[i] ^= a[k];
    a[k] ^= a[i];
    a[i] ^= a[k];
}

暫無
暫無

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

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