如何在C#中将数组的所有元素从左侧移到右侧

时间:2019-11-15 23:58:43

标签: c# arrays sorting

我正在尝试从最左边一直到最右边交换数组的元素。

所以数组看起来像这样:1234567

我希望输出是这样的: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;
    }

谢谢您的建议!

4 个答案:

答案 0 :(得分:3)

如果要更改数组本身的顺序(不创建新数组),可以使用以下命令:

Array.Reverse(array);

答案 1 :(得分:1)

您可以使用<template> <div style="width:auto; height:auto; display:flex; flex-direction.column;"> <button @click="editorVisible = true">Show Editor</button> <vue-editor v-model="pvalue" :editorToolbar="customToolbar" useCustomImageHandler @imageAdded="handleImageAdded"></vue-editor> </div> </template> <!--SCRIPTS--> <script> import { VueEditor } from 'vue2-editor'; export default { props: { value:{ required:true, type:String } }, data() { return { pvalue: '', } }, watch: { value(val){ this.pvalue = val; }, pvalue(val){ this.$emit('input', val); } } } </script> 中的方法v-model="pvalue"

Reverse

答案 2 :(得分:1)

为什么不按降序遍历数组?

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

答案 3 :(得分:1)

如果您不想使用任何预构建的.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 Fiddle

相关问题