C#代码到数组中的左移位元素 [英] C# code to left shift elements in an array
问题描述
hi team,
我有一个数组低于元素和索引的数组
arr [5] =   a,d,e,f,g
index 0,1,2,3,4
I have an array with below element and index
arr[5] = a, d, e, f, g
index 0, 1, 2, 3, 4
对于给定src和目标位置我想移动元素
Ex:srcpos = 1,targetpos = 4 ,位置1的元素(srcpos)现在被移动到trgpos(4)并且e,f,g被左移#B $ b我需要使用for循环来实现相同的结果。
结果数组将
For a give src and target postion i want to move the elements
Ex: srcpos = 1, targetpos = 4, element at position 1(srcpos) is now moved to trgpos(4) and e,f,g got left shifted
I need to use for loop to achieve the same.
Result array will be
res [5] = a,e,f,g,d
$
index 0,1,2,3,4
res[5] = a, e, f, g, d
index 0, 1, 2, 3, 4
任何人都可以共享相同的代码段。   ; 
Can anyone share code snippet for the same.
推荐答案
嗨!
请尝试以下代码
class Program {
static void Main(string[] args) {
char[] arr = new char[] { 'a', 'd', 'e', 'f', 'g' };
Print(arr);
Shift(arr, 1, 4);
Console.WriteLine();
Print(arr);
Console.ReadKey();
}
public static void Print(char[] array) {
foreach (var c in array)
Console.Write(c);
}
public static void Shift(char[] array, int src, int dst) {
if (src == dst)
return;
if (src < dst) {
var target = src + 1;
var temporaryItem = array[target];
array[target] = array[src];
array[src] = temporaryItem;
src = target;
}
if (src > dst) {
var target = src - 1;
var temporaryItem = array[target];
array[target] = array[src];
array[src] = temporaryItem;
src = target;
}
Shift(array, src, dst);
}
}
老实说,使用List代替数组要容易得多:
Honestly, it is much more easy to work with List instead of array:
var list = new List<char> { 'a', 'd', 'e', 'f', 'g' };
var sourceIndex = 1;
var targetIndex = 4;
var soruceItem = list[1];
list.RemoveAt(sourceIndex);
list.Insert(targetIndex, soruceItem);
这篇关于C#代码到数组中的左移位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!