我有一個int數組,包含從索引0開始的一些值。我想交換兩個值,例如索引0的值應與索引1的值交換。我怎麼能在c#數組中執行此操作?如何在c#中交換數組的兩個值?
-5
A
回答
3
如果你真的只想要交換,你可以用這個方法:
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 buffer = array[x];
array[x] = array[y];
array[y] = buffer;
return true;
}
x和y的indizies,應當調換。
如果你想與任何類型的陣列來交換,那麼你可以做這樣的:
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 buffer = objectArray[x];
objectArray[x] = objectArray[y];
objectArray[y] = buffer;
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!");
return;
}
1
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
}
調用這個函數和打印elemet
1
只交換兩個值只有一次或想要爲整個陣列做同樣的事情。
假設你只希望交換隻有兩個只有一次,是整數類型的,那麼你可以試試這個:
int temp=0;
temp=arr[0];
arr[0]=arr[1];
arr[1]=temp;
0
我只寫類似的東西,所以這裏是一個版本,
- 使用泛型,使其適用於整數,字符串等,
- 使用擴展方法
- 配有測試類
享受:)
[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;
}
}
4
您可以創建一個擴展方法,將任何陣列
public static void SwapValues<T>(this T[] source, long index1, long index2)
{
T temp = source[index1];
source[index1] = source[index2];
source[index2] = temp;
}
工作
相關問題
- 1. C++內置交換兩個數值?
- 2. 在C++中隨機交換數組中的兩個元素
- 3. 如何在Java的方法中交換兩個整數的值?
- 4. 如何用數組值替換數組值[有兩個數組]
- 5. 如何在C#中替換數組值?
- 6. Swift:如何交換四維數組中的兩個軸?
- 7. 如何交換兩個SyntaxNode(Roslyn C#)
- 8. 在C中交換兩個向量
- 9. C# - 比較兩個數組中的值
- 10. 交換兩個數組而不完全分配第三個(C++)
- 11. 如何在C++中使用哈希函數找到兩個數組的交集?
- 12. 交換c中的兩個結構
- 13. 交換SQL Server表中的兩個值
- 14. 交換兩個數組元素
- 15. 如何在C中定時交換兩個矩陣?
- 16. 如何交換C中鏈接列表中的兩個節點?
- 17. 在C++中使用2d數組交換
- 18. 如何相交兩個數組?
- 19. 如何交換字典中的兩個隨機值?
- 20. 需要交換java中的數組中的兩個元素
- 21. 交換數組中的對象 - C#
- 22. 在MIPS中交換兩個數組元素
- 23. 在兩行數據之間交換值
- 24. 如何從Rust中的多維數組中交換值?
- 25. 在C++中相互交換數組的各個部分
- 26. 如何比較兩個數組的值?
- 27. 如何在GNU make函數中交換兩個文件?
- 28. C - 數組內容交換
- 29. 使用交換機多個值在數組中的PHP
- 30. 交換中的元組(蟒蛇)名單的兩個數字