c# - 反转数组中的元素

标签 c# arrays reverse

我设置了一个数组,我想创建一个方法来返回一个元素相反的数组。例如如果有 10 个插槽,则 array1[9] = 6 那么 array2[0] = 6
我想我必须返回一个数组——我该怎么做?
而且我不知道如何反转并添加到另一个数组。
谢谢你!

        int[] arr = {43, 22, 1, 44, 90, 38, 55, 32, 31, 9};
        Console.WriteLine("Before");
        PrintArray(arr);
        Console.WriteLine("After");
        Reverse(arr);

         Console.ReadKey(true);

    }

    static int[] Reverse(int[] array)
    {
        for (int i = array.Length; i < 1; i--)
        {
            int x = 0;

            array[i] = array[x++];
            Console.WriteLine(array[i]);
        }

       }


         static void PrintArray(int[] array)
    {
        for (int j = 0; j < array.Length; j++)
        {
            Console.Write(array[j] + " ");

        }
        Console.WriteLine("");

最佳答案

您可以使用 Array.Reverse

上面一行的例子

public static void Main()  {

  // Creates and initializes a new Array.
  Array myArray=Array.CreateInstance( typeof(String), 9 );
  myArray.SetValue( "The", 0 );
  myArray.SetValue( "quick", 1 );
  myArray.SetValue( "brown", 2 );
  myArray.SetValue( "fox", 3 );
  myArray.SetValue( "jumps", 4 );
  myArray.SetValue( "over", 5 );
  myArray.SetValue( "the", 6 );
  myArray.SetValue( "lazy", 7 );
  myArray.SetValue( "dog", 8 );

  // Displays the values of the Array.
  Console.WriteLine( "The Array initially contains the following values:" );
  PrintIndexAndValues( myArray );

  // Reverses the sort of the values of the Array.
  Array.Reverse( myArray );

  // Displays the values of the Array.
  Console.WriteLine( "After reversing:" );
  PrintIndexAndValues( myArray );
}


public static void PrintIndexAndValues( Array myArray )  {
  for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
     Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
}

关于c# - 反转数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394882/

相关文章:

Javascript/Angular 在洗牌后返回数组

c - 读入数组直到文件末尾

swift - 需要帮助让 swift 应用程序正确显示标签上的反向字符串

javascript - 反向链接列表 - Javascript - 使用类还是只是定义一个函数?以及如何计算时间/空间复杂度

c# - 将 Kinect 与 Emgu CV 结合使用

c# - Visual Studio IDE0059 C# 不必要的值赋值错误?

c# - 小型集合中 linq 和 INTERSECT/EXCEPT 的低性能

c# - Linq to sql/C# - 多处搜索键/值对

python - Numpy:将大型数组与 dtype=int8 相乘很慢

jquery - 获取索引 REVERSED 中的元素位置