反转数组中的元素

编程入门 行业动态 更新时间:2024-10-24 00:18:27
本文介绍了反转数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I setup an array and i would like to create a method that will return an array with the elements in reverse. e.g. if there are 10 slots then array1[9] = 6 so then array2[0] = 6. I suppose i have to return an array - how would i do that? And i dont know how to reverse and add to another array. Thank you!

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 ) ); }

更多推荐

反转数组中的元素

本文发布于:2023-06-04 08:33:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/493322.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   转数   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!